.NET IdentityModel.JsonWebTokens how to validate token?

34 views Asked by At

I am using the IdentityModel.JsonWebTokens package to create my JsonWebToken.

This is the code that creates the token:

        public string CreateToken(User user)
    {
        byte[] secret = Encoding.UTF8.GetBytes(configuration.JwtKey);
        SymmetricSecurityKey key = new SymmetricSecurityKey(secret);

        Dictionary<string, object> claims = new Dictionary<string, object>
        {
            [ClaimTypes.NameIdentifier] = user.Id,
            [ClaimTypes.Name] = user.Username,
            [ClaimTypes.Email] = user.Email
        };

        SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor
        {
            Claims = claims,
            SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature)
        };

        JsonWebTokenHandler handler = new JsonWebTokenHandler();
        handler.SetDefaultTimesOnTokenCreation = false;
        string token = handler.CreateToken(descriptor);
        return token;
    }

This is the code that I used in my previous application using the AspNetCore.Authentication.JwtBearer package:

The token creation:

        public string CreateToken(User user)
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
            new Claim(ClaimTypes.Name, user.Email),
            new Claim(ClaimTypes.Role, user.Role.Name),
        };

        var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(configuration.GetSection("AppSettings:Token").Value!));
        var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
        var token = new JwtSecurityToken(
            claims: claims,
            expires: DateTime.Now.AddDays(1),
            signingCredentials: credentials
        );

        var jwt = new JwtSecurityTokenHandler().WriteToken(token);
        return jwt;
    }

And this is my code in the Program.cs:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(
            System.Text.Encoding.UTF8.GetBytes(builder.Configuration.GetSection("AppSettings:Token").Value)
        ),
        ValidateIssuer = false,
        ValidateAudience = false
    };
});

How can I update this code so it uses the IdentityModel.JsonWebTokens package ?

0

There are 0 answers