首页 > 解决方案 > 将 JWT 从客户端发送到服务器

问题描述

我想在 ASP.NET Core 2.2 中使用 JWT 身份验证,我从 Postman 的正文和标头发送 Token,但收到 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();
    });
});

标签: c#asp.net-core

解决方案


确保您的请求是否包含authorization具有以下值的标头Bearer access_token

Authentication: Bearer KJVG32532UVBU78V...

推荐阅读