How validate JWT token in asp.net core web application

Last Reply 10 days ago By dharmendr

Posted 10 days ago

i have genetared JWT token in when user login after i tryting to access the below controller its throwing 401-Unauthrized error.

  string key = "DD62DAA7-4E9E-405D-BC9E-5A5508233843"; //this should be same which is used while creating token      
            var issuer = "LittlePacktBookStore";  //this should be same which is used while creating token  
            var Audience = "App_User";


            //internal static readonly string Key = "DD62DAA7-4E9E-405D-BC9E-5A5508233843";
            //internal static readonly string Issuer = "LittlePacktBookStore";
            //internal static readonly string Audience = "App_User";

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
          .AddJwtBearer(options =>
          {
              options.TokenValidationParameters = new TokenValidationParameters
              {
                  ValidateIssuer = true,
                  ValidateAudience = true,
                  ValidateIssuerSigningKey = true,
                  ValidIssuer = issuer,
                  ValidAudience = Audience,
                  IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key))
              };

              options.Events = new JwtBearerEvents
              {
                  OnAuthenticationFailed = context =>
                  {
                      if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                      {
                          context.Response.Headers.Add("Token-Expired", "true");
                      }
                      return Task.CompletedTask;    
                  }
              };
          });

How to validate the token JWT below is my token

eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ2ZW5rYXRAZ21haWwuY29tIiwidW5pcXVlX25hbWUiOiJ2ZW5rYXRAZ21haWwuY29tIiwianRpIjoiNDE1MzdhZTctODJkOS00OGE2LWI3N2EtNDk5MDZlNWVmM2NkIiwiZXhwIjoxNjA1NzgwMjczLCJpc3MiOiJMaXR0bGVQYWNrdEJvb2tTdG9yZSIsImF1ZCI6IkFwcF9Vc2VyIn0.GIJAlU7p8eaq4vC2J8nQBb3y2rGdX2psHwqlFxt9KwWAJMG2sUG970sNYOflj6GjUBA4GGQmtrZigQiBc1GQUA

You are viewing reply posted by: dharmendr 10 days ago.
Posted 10 days ago