[英]ASP.Net Core 3.0 JWT Bearer Token No SecurityTokenValidator available
[英]Authentication based on JWT token bearer fails under .NET Core 2.2 after move from 3.0
我采用了具有有效身份验证的解决方案,并将其从Core 3.0降级为Core 2.2。 之后,安装程序停止工作。 显然,我所缺少的组织方式略有不同。 与博客和演练相比,我看不到它。
认证配置如下。 非常简单,目前仅检查时间戳。
TokenValidationParameters parameters = new TokenValidationParameters
{
ValidateLifetime = true,
ValidateAudience = false,
ValidateIssuer = false,
ValidIssuer = "https://localhost:44385",
ValidAudience = "https://localhost:44385"
};
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(config => config.TokenValidationParameters = parameters);
使用以下代码发行令牌。
TokenValidationParameters parameters = ...
byte[] secret = Encoding.UTF8.GetBytes("my_top_secret");
SecurityKey key = new SymmetricSecurityKey(secret);
SigningCredentials credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
JwtSecurityToken jwt = new JwtSecurityToken(
"https://localhost:44385",
"https://localhost:44385",
{ new Claim("a", "b") },
DateTime.Now,
DateTime.Now.AddSeconds(3600),
credentials
);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);
return Ok(new { token });
返回的值似乎正确,并且我已在JWT.IO上对其进行了验证,因此我不怀疑这是问题所在。 但是,当我将该值粘贴到Postman中时(就像我之前一切正常时所做的那样),它会给我401。
我不确定是什么问题,但是我感觉到它与我在Startup类中配置身份验证的方式有关。 我在这里和这里使用的参考书应该看起来如何。
我想念什么? 另外,我还能如何解决它?
感谢@LGSon的评论,我意识到了问题所在。 由于某些奇怪和无法解释的原因,必须在参数中指定IssuerSigningKey
。 如果ValidateIssuerSigningKey
的值设置为true
是有意义的,但是在我的情况下,我默认情况下为false
。
TokenValidationParameters parameters = ...;
parameters.IssuerSigningKey = Configuration.GetSecurityKey();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(config => config.TokenValidationParameters = parameters);
在Core 2.2中,无论是否使用它,都必须指定它。 在Core 3.0(至少在最新的预览版中)不是! 在我看来,这是一个偷偷摸摸的陷阱(已更正的边界错误)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.