【问题标题】:JWT Bearer Authentication and Authorization not working, because of TokenValidationParameters由于 TokenValidationParameters,JWT 承载身份验证和授权不起作用
【发布时间】:2020-10-16 02:56:47
【问题描述】:

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

JwtAuthenticationService.cs是我为生成Token而做的一个类。

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);
}

这是我的登录控制器

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;
}

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

 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
                };
            });

当我将这些参数 ValidateIssuerValidateAudience 更改为 true 时,API 不允许我访问控制器并重定向我。

这是我的 appsettings.json

"Jwt": {
    "SecretKey": "SomeSecretKey",
    "Issuer": "https://localhost:44393/",
    "Audience": "https://localhost:44301/"
  },

【问题讨论】:

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


    【解决方案1】:

    您在调用该端点时必须包含该令牌,因为它现在受到保护。您可以在浏览器的本地存储或 cookie 中获取令牌,具体取决于您的存储方式。

    然后把你的令牌放在这里:

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

    【讨论】:

    • 它仍然无法正常工作,问题可能是因为我将身份用于登录/注册功能吗?这是我在 API imgur.com/a/fKX0ttH 中向登录控制器发出 Post 请求时得到的结果@
    • 您的 API 中有 authentication scheme = "Bearer" 吗?请尝试一下。
    【解决方案2】:

    当我将这些参数 ValidateIssuer 或 ValidateAudience 更改为 true 时,API 不会让我访问控制器并重定向我。

    因为生成的令牌中没有IssuerAudience

    如果要更改为ValidateIssuerValidateAudience 的true,请如下更改:

    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));
    

    【讨论】:

      猜你喜欢
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 2017-07-21
      • 2015-05-12
      • 2021-07-17
      • 2013-11-15
      • 1970-01-01
      • 2013-04-17
      相关资源
      最近更新 更多