title: Problem with JWT Token while Authenticating the user
body: <p>I have web api which is authorized and i have implemented JWT refresh Token security and everything works fine. When I enter valid password and username it response me back accesstoken and refeshtoken.</p>
  <p>So the problem is that when i request token i get it back and that token expires in 1 day but when i change user credentials like password and role and even if send request using old token i stay authenticated or system allows me to access the resources.</p>
  <p>Here is my API</p>
  <pre><code>    [Route(&quot;api/[controller]&quot;)]
      [ApiController]
      public class ValuesController : ControllerBase
      {
          [HttpGet]
          public ActionResult&lt;string&gt; Foo()
          {
              return &quot;Hello World&quot;;
          }
      }
  </code></pre>
  <p>Here is my startup class's Configure method</p>
  <pre><code>        public void ConfigureServices(IServiceCollection services)
          {
              var tokenKey = &quot;This is my secret key of the token&quot;;
              var key = Encoding.ASCII.GetBytes(tokenKey);
  
              services.AddAuthentication(options =&gt;
              {
                  options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                  options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
              }).AddJwtBearer(options =&gt;
              {
                  options.RequireHttpsMetadata = false;
                  options.SaveToken = true;
                  options.TokenValidationParameters = new TokenValidationParameters
                  {
                      ValidateIssuerSigningKey = true,
                      IssuerSigningKey = new SymmetricSecurityKey(key),
                      ValidateIssuer = false,
                      ValidateAudience = false,
                      ClockSkew = TimeSpan.FromDays(10)
                  };
                  options.Events = new JwtBearerEvents
                  {
                      OnAuthenticationFailed = context =&gt;
                      {
                          if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                          {
                              context.Response.Headers.Add(&quot;Token-Expired&quot;, &quot;true&quot;);
                          }
                          return Task.CompletedTask;
                      }
                  };
              });
  
              services.AddControllersWithViews(option =&gt;
              {
                  var policy = new AuthorizationPolicyBuilder()
                                  .RequireAuthenticatedUser()
                                  .RequireRole(&quot;Consumer&quot;, &quot;Admin&quot;)
                                  .Build();
                  option.Filters.Add(new AuthorizeFilter(policy));
              });
              services.AddSwaggerGen(c =&gt;
              {
                  c.SwaggerDoc(&quot;v1&quot;, new OpenApiInfo { Title = &quot;CodeFactoryAPI&quot;, Version = &quot;v1&quot; });
              });
  
              services.AddDbContextPool&lt;AdminContext&gt;(opt =&gt; opt.UseSqlServer(Configuration.GetConnectionString(&quot;CodeFactoryAPI&quot;)));
              services.AddSingleton&lt;string&gt;(tokenKey);
          }
  </code></pre>
  <p>Here is the code that generates JWT token</p>
  <pre><code>    public class AuthenticationService : IDisposable
      {
          private AdminContext context;
          private bool disposed = false;
          private readonly string tokenKey;
  
          public AuthenticationService(AdminContext context, string tokenKey)
          {
              this.context = context;
              this.tokenKey = tokenKey;
          }
  
          public async Task&lt;(string accessToken, string refeshToken)&gt; Authenticate(string userName, string password)
          {
              var consumer = await context.Users.FirstOrDefaultAsync(u =&gt; u.ConsumerName == userName &amp;&amp;
                                                                      u.Password == password);
              if (consumer is null)
                  return default;
  
              consumer.Token = GenerateRefreshToken();
              consumer.IssuedToken = DateTime.Today;
  
              var tokenHandler = new JwtSecurityTokenHandler();
              var key = Encoding.ASCII.GetBytes(tokenKey);
  
              Claim[] claims = new Claim[] { new(ClaimTypes.Name, userName + ',' + password), new(ClaimTypes.Role, consumer.Role) };
  
              var tokenDescriptor = new SecurityTokenDescriptor
              {
                  Subject = new ClaimsIdentity(claims),
                  Expires = DateTime.UtcNow.AddDays(1),
                  SigningCredentials = new(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
              };
              var token = tokenHandler.CreateToken(tokenDescriptor);
  
              context.Update(consumer);
              await context.SaveChangesAsync().ConfigureAwait(false);
  
              return (tokenHandler.WriteToken(token), consumer.Token);
          }
  
          public async Task&lt;(string accessToken, string refeshToken)&gt; ReAuthenticate(string refreshToken)
          {
              var consumer = await context.Users.FirstOrDefaultAsync(u =&gt; u.Token == refreshToken)
                                                .ConfigureAwait(false);
              if (consumer is null || consumer.IssuedToken == null || (DateTime.Today - consumer.IssuedToken.Value).Days &gt; 30)
                  return default;
  
              consumer.Token = GenerateRefreshToken();
              consumer.IssuedToken = DateTime.Today;
  
              var tokenHandler = new JwtSecurityTokenHandler();
              var key = Encoding.ASCII.GetBytes(tokenKey);
              var claims = new Claim[] { new(ClaimTypes.Name, consumer.ConsumerName + ',' + consumer.Password) };
  
              var tokenDescriptor = new SecurityTokenDescriptor
              {
                  Subject = new ClaimsIdentity(claims),
                  Expires = DateTime.UtcNow.AddDays(1),
                  SigningCredentials = new(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
              };
  
              var tokens = tokenHandler.CreateToken(tokenDescriptor);
              var acceessToken = tokenHandler.WriteToken(tokens);
  
              context.Update(consumer);
              await context.SaveChangesAsync().ConfigureAwait(false);
  
              return (acceessToken, consumer.Token);
          }
  
          public string GenerateRefreshToken()
          {
              var randomNumber = new byte[32];
              using var rng = RandomNumberGenerator.Create();
              rng.GetBytes(randomNumber);
              return Convert.ToBase64String(randomNumber);
          }
  
          public void Dispose()
          {
              Dispose(true);
          }
  
          public void Dispose(bool disposing)
          {
              if (!disposed)
              {
                  if (disposing)
                  {
                      context.Dispose();
                  }
                  context = null;
                  disposed = true;
              }
          }
      }
  </code></pre>
  <p>so when i update any users data and even if try to access resource i can.</p>
  <p>here is screenshot</p>
  <p><a href="https://i.stack.imgur.com/P0qla.png" rel="nofollow noreferrer">enter image description here</a></p>
  <p>then if i update user data like username and password</p>
  <p><a href="https://i.stack.imgur.com/c3jZy.png" rel="nofollow noreferrer">enter image description here</a></p>
  <p>and i try to access resource using old token i stay authenticated</p>
  <p><a href="https://i.stack.imgur.com/K1wRT.png" rel="nofollow noreferrer">enter image description here</a></p>
  <p>What is causing the problem and how to fix this?</p>