简体   繁体   中英

C# Authorization JWT token

I have an issue with Postman. When generating token truth swagger I get JWT. When checking the token in jwt.io it can read the token jwti.io success

But when adding it in postman it shows error 401. postman 401

Does anyone know what the issue could be?

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

The mistake was in 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"]))
    });

On the last line builder.Configuration["Jwt:Key"] , i had added before builder.Configuration["Jwt:Audience"] . Changing it to Key fixed it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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