为什么我有有效的Token却得不到授权?

问题描述 投票:0回答:1

通过此方法生成token:

 private string GenerateJwtToken(User user)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            var base64Key = _configuration["Jwt:Secret"];

            try
            {
                var key = Convert.FromBase64String(base64Key);

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Issuer = _configuration["Jwt:Issuer"],
                    Audience = _configuration["Jwt:Audience"],
                    Subject = new ClaimsIdentity(
                        new Claim[]
                        {
                            new Claim(ClaimTypes.Name, user.Email),
                            new Claim("UserId", user.ID.ToString())
                        }
                    ),
                    Expires = DateTime.UtcNow.AddDays(14),
                    SigningCredentials = new SigningCredentials(
                        new SymmetricSecurityKey(key),
                        SecurityAlgorithms.HmacSha256Signature
                    )
                };

                var token = tokenHandler.CreateToken(tokenDescriptor);
                return tokenHandler.WriteToken(token);
            }
            catch (FormatException ex)
            {
                Console.WriteLine($"error converting Base64 string: {ex.Message}");
                return null;
            }
        }
    ``` 

I checked on jwt.io and it says the token generated is valid.

When I use thunderclient to my /user endpoint to get the user by passing the JWT token in the header then I get Status: 401 Unauthorized.

Here is my post method:

    [HttpPost]
    [Authorize]
    public async Task<ActionResult<UserDTO>> GetUserDTO()
    {
        Console.WriteLine("I GET USER");
        try
        {
            var jwt = HttpContext.Request.Headers["Authorization"]
                .ToString()
                .Replace("Bearer ", string.Empty);

            Console.WriteLine(jwt);
            if (string.IsNullOrWhiteSpace(jwt))
            {
                return BadRequest("JWT token is missing.");
            }
            var loggedInUser = _userService.GetByJWT(jwt);

            if (loggedInUser == null)
            {
                return BadRequest("Failed to get user.");
            }

            return Ok(loggedInUser.FirstName);
        }
        catch (Exception e)
        {
            return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
        }
    }
```

当我删除 [Authorize] 时,它就可以工作,并且可以解析 JWT 持有者的 id。

在program.cs中,我有我的授权模式并尝试更改它,看看我的发行者或受众是否有问题?我将发行者值设置为应用程序名称,将受众值设置为 API,因为 API 将使用它。那是对的吗?这是架构:

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Secret"])
            ),
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Audience"]
        };
    });

builder.Services.AddAuthorization();

为什么我会被未经授权?

c# api jwt token webapi
1个回答
0
投票

问题是您使用了两个不同的键,请参阅以下行:

var key = Convert.FromBase64String(base64Key); //used to generate a jwt

IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Secret"])
            ) // used to check a jwt

基本上

Encoding.UTF8.GetBytes
Convert.FromBase64String(base64Key)
对于相同的字符串不会返回相同的
byte[]

© www.soinside.com 2019 - 2024. All rights reserved.