简体   繁体   English

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

[英]JWT Bearer Authentication and Authorization not working, because of TokenValidationParameters

I am trying to make WEB API using .NET Core 3.1 and make Client Application that uses that API for all the server stuff.我正在尝试使用 .NET Core 3.1 制作 WEB API 并制作使用 ZDB974238714CA8DE634A7CED 的所有服务器的客户端应用程序。 for the Client App I am using ASP.Net Core 3.1 MVC.对于客户端应用程序,我使用的是 ASP.Net Core 3.1 MVC。
On my API I am trying to make JWT Bearer Authentication and Authorization.在我的 API 上,我正在尝试进行 JWT 承载身份验证和授权。

JwtAuthenticationService.cs is a class I made to generate Token. JwtAuthenticationService.cs是我用来生成 Token 的 class。

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

This is my Login controller这是我的登录名 controller

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

I managed to determine that the problems is in my TokenValidationParameters我设法确定问题出在我的 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
                };
            });

When I change to true of these parameters ValidateIssuer or ValidateAudience the API does not give me access to the controller and redirects me.当我将这些参数ValidateIssuerValidateAudience更改为 true 时,API 不会让我访问 controller 并重定向我。

This is my appsettings.json这是我的 appsettings.json

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

You must include the token when you call that endpoint because it is now protected.调用该端点时必须包含该令牌,因为它现在受到保护。 You can either get your token in your browser's localstorage or cookies depending on how you store it.您可以在浏览器的本地存储或 cookies 中获取令牌,具体取决于您的存储方式。

Then place your token here:然后将您的令牌放在这里:

在此处输入图像描述

Add [Authorize(AuthenticationSchemes = "Bearer")] on top of your Login controller to check headers with Bearer tokens.在您的登录 controller 顶部添加[Authorize(AuthenticationSchemes = "Bearer")]以检查带有不记名令牌的标头。

When I change to true of these parameters ValidateIssuer or ValidateAudience the API does not give me access to the controller and redirects me.当我将这些参数 ValidateIssuer 或 ValidateAudience 更改为 true 时,API 不会让我访问 controller 并重定向我。

Because there is no Issuer and Audience in the generated token.因为生成的token中没有IssuerAudience

If you want to change to the true of ValidateIssuer or ValidateAudience ,change like below:如果要更改为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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM