JWT承载令牌身份验证在ASP.NET核心Web API中失败

ifmq2ha2  于 2023-04-22  发布在  .NET
关注(0)|答案(1)|浏览(159)

我有一个使用JWT Bearer令牌身份验证设置的ASP.NET Core Web API应用程序,我遇到了令牌验证失败的问题。我已经使用Postman测试了令牌,它也不起作用。问题似乎在服务器端。
下面是在我的Startup.cs中设置身份验证的相关代码:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = jwtAuth.Issuer,
            ValidateAudience = true,
            ValidAudience = jwtAuth.Audience,
            ValidateLifetime = true,
            IssuerSigningKey = jwtAuth.GetSecurityKey(),
            ValidateIssuerSigningKey = true,
        };
    });

下面是生成JWT令牌的代码:

var authClaims = new List<Claim>
  {
      new (ClaimTypes.Name, user.UserName!),
      new (JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
  };

// No role claims are added since I'm not using roles

var token = new JwtSecurityTokenHandler().WriteToken(_jwtConfiguration.GetToken(authClaims));

获取令牌方法:

public JwtSecurityToken GetToken(IEnumerable<Claim> claims)
    {
        return new JwtSecurityToken(
            issuer: Issuer,
            audience: Audience,
            notBefore: DateTime.Now,
            claims: claims,
            expires: DateTime.Now.Add(TimeSpan.FromMinutes(LifetimeInMinutes)),
            signingCredentials: new SigningCredentials(GetSecurityKey(), SecurityAlgorithms.HmacSha256));
    }

下面是带有[Authorize]属性的安全方法:

[HttpPost("/auth/test")]
[Authorize]
public async Task<ActionResult> TestAuthorization()
{
    return Ok();
}

当我使用Postman或我的Flutter客户端测试时,我得到以下错误:

[23:35:31 INF] Request starting HTTP/1.1 POST http://10.0.2.2:5180/auth/test - 0
[23:35:31 INF] Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
[23:35:31 INF] AuthenticationScheme: Bearer was challenged.
[23:35:31 INF] Request finished HTTP/1.1 POST http://10.0.2.2:5180/auth/test - 0 - 401 0 - 30.5047ms

顺便说一下,这是我的Flutter代码:

final url = Uri.parse("${Config.baseUrl}/auth/google");

final Map response = json.decode((await http.post(url, body: {
  'code': signIn?.serverAuthCode,
}))
    .body);

final result = response['result'] as Map;

await http.post(Uri.parse('${Config.baseUrl}/auth/test'), headers: {
  HttpHeaders.authorizationHeader: 'Bearer ${result['accessToken']}',
});

我试着用这种方式生成一个token:

var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(authClaims),
    Expires = DateTime.UtcNow.AddHours(1),
    SigningCredentials = new SigningCredentials(jwtAuth.GetSecurityKey(), SecurityAlgorithms.HmacSha256Signature),
    Issuer = jwtAuth.Issuer,
    Audience = jwtAuth.Audience,
};

var tokenHandler = new JwtSecurityTokenHandler();
var securityToken = tokenHandler.CreateToken(tokenDescriptor);
var accessToken = tokenHandler.WriteToken(securityToken);
yhuiod9q

yhuiod9q1#

我把

app.UseAuthentication();

之前

app.UseAuthorization();

这解决了我的问题

相关问题