我想在ASP.NET Core 2.2中使用JWT身份验证, 我从邮递员的正文和标头发送令牌,但收到401错误,
用于创建令牌的代码:
var signature = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Test API For JWT Authentication in ASP.NET Core 2.2"));
var header = new SigningCredentials(signature, SecurityAlgorithms.HmacSha256);
var payload = new JwtSecurityToken(claims: new List<Claim>
{
new Claim(ClaimTypes.Name, userInfo.Username)
} , signingCredentials:header);
var token = new JwtSecurityTokenHandler().WriteToken(payload);
return token;
startup.cs配置:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Test API For JWT Authentication in ASP.NET Core 2.2"))
};
});
services.AddCors(options =>
{
options.AddPolicy("Cors", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.Build();
});
});
答案 0 :(得分:1)
确保您的请求中是否包含authorization
标头,其值为Bearer access_token
:
Authentication: Bearer KJVG32532UVBU78V...