postman C#授权JWT标记

axr492tv  于 2022-11-07  发布在  Postman
关注(0)|答案(1)|浏览(174)

我遇到了一个与Postman有关的问题。当生成令牌truth swagger时,我得到了JWT。当在www.example.com中检查令牌时jwt.io,它可以读取令牌jwti.io success
但在postman中添加时,显示错误401. postman 401
有人知道问题出在哪里吗?

public class TokenHandler : ITokenHandler
{
    private readonly IConfiguration _configuration;
    public TokenHandler(IConfiguration configuration)
    {
        this._configuration = configuration;
    }
    public Task<string> CreateTokenAsync(User user)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));

        // create Claims
        var claims = new List<Claim>();

        claims.Add(new Claim(ClaimTypes.GivenName, user.FirstName));
        claims.Add(new Claim(ClaimTypes.Surname, user.LastName));
        claims.Add(new Claim(ClaimTypes.Email, user.EmailAddress));

        //loop into roles of users
        user.Roles.ForEach((role) =>
        {
            claims.Add(new Claim(ClaimTypes.Role, role));
        });

        var credentials = new SigningCredentials(key,SecurityAlgorithms.HmacSha256);
        var token = new JwtSecurityToken(
            _configuration["Jwt:Issuer"],
            _configuration["Jwt:Audience"],
            claims,
            expires: DateTime.Now.AddMinutes(15),
            signingCredentials: credentials);

        return Task.FromResult(new JwtSecurityTokenHandler().WriteToken(token));
    }
lyfkaqu1

lyfkaqu11#

错误在Program.cs中

//injected token validations by me
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => options.TokenValidationParameters =
    new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes
        (builder.Configuration["Jwt:Key"]))
    });

在最后一行builder.Configuration["Jwt:Key"]上,我在builder.Configuration["Jwt:Audience"]之前添加了它。将其更改为Key修复了它

相关问题