Posts

....
Technical Blog for .NET Developers ©

Saturday, May 25, 2024

JWT Token Validation

There are different ways and technologies to validate a JWT Token, depending on the needs of securization of the infrastructure

This article deepens on theories and techniques of JWT Token validation: How to Validate JWTs in .NET

In this example we implement automatic validation with ASP.NET Core middleware, making emphasis on validate these pieces of the token: issuer, audience, and expiration time, which are the basic pieces to be validated



With this code we generate a JWT Token, codified in a string composed by header, payload, and signature

 

    public string GenerateToken(string user)
    {
        JwtSecurityTokenHandler tokenHandler = new ();
        byte[] key = Encoding.ASCII.GetBytes("B88CF37BEEE14F9DAA10DA3BDF23D9CA6EBD06E27A6D49C2867A211685A41E88");
        SecurityTokenDescriptor tokenDescriptor = new ()
        {
            Subject = new ClaimsIdentity(new[] { new Claim("id", "user_Id") }),
            Expires = DateTime.UtcNow.AddMinutes(1),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
            Issuer = "https://authdomain",
            Audience = "the_audience",            
            IssuedAt = DateTime.UtcNow,
            Claims = new Dictionary<string, object> { ["claim1"] = "test" }
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }





To validate the token from the api, configure the token at IoC to validate it as it is created originally from the source

 
  
        public static void ConfigureJWTToken(this IServiceCollection services, IConfiguration configuration)
        {
            byte[] key = Encoding.ASCII.GetBytes("B88CF37BEEE14F9DAA10DA3BDF23D9CA6EBD06E27A6D49C2867A211685A41E88");

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
              .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
              {
                  options.Audience = configuration["Auth:Audience"];
                  //options.Authority : Gets or sets the Authority to use when making OpenIdConnect calls.
                  options.TokenValidationParameters =
                    new TokenValidationParameters
                    {
                        ValidateAudience = true,
                        AudienceValidator = new AudienceValidator((audiences, token, options) =>
                        {
                            // audience validator logic
                            return true;
                        }),
                        ValidateLifetime = true,
                        ClockSkew = TimeSpan.Zero,
                        ValidateIssuer = true,
                        ValidIssuer = "https://authdomain",
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(key),
                    };
              });
        }  
  


METHOD SOFTWARE 2024