我从字面上读过互联网,尝试了多种方法,等等-没运气。
我正在尝试创建一个非常小的WebApi项目,其中包含一些受jwt令牌保护的控制器。
我使用以下代码生成令牌:
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("may the force"));
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims.ToArray()),Expires = DateTime.UtcNow.AddDays(7),SigningCredentials = new SigningCredentials(secretKey,SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
我已经在(Startup.cs)中设置了身份验证位
services.AddAuthentication(x => {
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}
)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,ValidateAudience = false,ValidateLifetime = true,ValidateIssuerSigningKey = true,IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("may the force"))
};
});
使用我的AuthController,我可以生成令牌(此问题中的第一个代码块)-并且需要“保护”的控制器用[Authorize]注释。
如果我从AuthController中获取结果并将其粘贴到https://jwt.io,则签名有效。
我正在使用邮递员测试控制器,并将请求标头的Authorization设置为Bearer
有人能指出我正确的方向吗?
非常感谢!
更新:我最初滥用jwt.io网站,因此下面的某些评论不再有效。
更新2:意识到服务器尝试使用基于cookie的身份验证。将注释更改为[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]可以解决问题-但仍不确定为什么