【问题标题】:Send JWT from Client to Server将 JWT 从客户端发送到服务器
【发布时间】:2019-04-22 16:49:05
【问题描述】:

我想在 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();
    });
});

【问题讨论】:

  • 你的 startup.cs 配置是什么?
  • @wandos 问题已更新
  • 你设置了ValidateIssuer = true但没有设置ValidIssuer

标签: c# asp.net-core


【解决方案1】:

确保您的请求是否包含值为Bearer access_tokenauthorization 标头:

Authentication: Bearer KJVG32532UVBU78V...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-15
    • 2015-05-02
    • 1970-01-01
    • 2011-08-15
    • 2013-04-11
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多