由于TokenValidationParameters,JWT承载身份验证和授权不起作用

时间:2020-06-25 15:29:02

标签: c# asp.net-core .net-core jwt asp.net-core-mvc

我试图使用.NET Core 3.1制作WEB API,并使所有服务器使用该API的客户端应用程序。对于客户端应用程序,我正在使用ASP .Net Core 3.1 MVC。
在我的API上,我尝试进行JWT承载身份验证和授权。

innerHTML是我用来生成令牌的类。

JwtAuthenticationService.cs

这是我的登录控制器

public async Task<String> GenerateJsonWebToken(ApplicationUser appUser)
{
    var claims = new List<Claim>
    {
        new Claim(ClaimTypes.Name, appUser.UserName),
        new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
        new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(5)).ToUnixTimeSeconds().ToString())
    };

    var roleNames = await _userManager.GetRolesAsync(appUser);

    foreach (var roleName in roleNames)
    {
        claims.Add(new Claim(ClaimTypes.Role, roleName));
    }
  

    var token = new JwtSecurityToken(
        new JwtHeader(
            new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:SecretKey"])),
            SecurityAlgorithms.HmacSha256)),
        new JwtPayload(claims));
            
    return new JwtSecurityTokenHandler().WriteToken(token);
}

我设法确定问题出在我的TokenValidationParameters

public async Task<IActionResult> Login([FromBody] POCOUser pocoUser)
{
    IActionResult response = Unauthorized();

    var appUser = await _userManager.FindByNameAsync(pocoUser.UserName);
    
   
    if ( await _userManager.CheckPasswordAsync(appUser, pocoUser.Password))
    {
        var tokenString = _jwtAuthenticationService.GenerateJsonWebToken(appUser);
        return Ok(new { token = tokenString });
    }

    return response;
}

当我将这些参数 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => { options.SaveToken = true; options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, // If I change to true it stops working ValidateAudience = false, // if I change to true it stops working. ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])), ClockSkew = TimeSpan.Zero }; }); ValidateIssuer设置为true时,API不会给我访问控制器的权限,而是重定向我。

这是我的appsettings.json

ValidateAudience

2 个答案:

答案 0 :(得分:1)

调用该端点时必须包含令牌,因为该令牌现在已受到保护。您可以根据自己的存储方式在浏览器的本地存储中获取令牌,也可以在Cookie中获取令牌。

然后将令牌放置在这里

enter image description here

在登录控制器顶部添加[Authorize(AuthenticationSchemes = "Bearer")],以检查带有Bearer令牌的标头。

答案 1 :(得分:0)

当我将这些参数ValidateIssuer或ValidateAudience更改为true时,API不会给我访问控制器的权限,而是将我重定向。

因为生成的令牌中没有IssuerAudience

如果要更改为ValidateIssuerValidateAudience的真值,请进行如下更改:

var token = new JwtSecurityToken(_config["Jwt:Issuer"],
    _config["Jwt:Audience"],
    claims: claims,
    expires: DateTime.Now.AddDays(5),
    signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:SecretKey"])),
        SecurityAlgorithms.HmacSha256));