title: ajax post request returns 400 Bad Request after refresh JWT Token
body: <p>ASP.NET Core MVC 5.</p>
  <p>I am using Cookie Authentication with JWT Token as Claims for login authentication.</p>
  <p>I also have an AutoValidateAntiForgeryToken attribute on each controller to deal with XSRF.</p>
  <p>The JWT Token is set to expire in 30 minutes.
  In my CookieAuthenticationEvents.ValidatePrincipal(CookieValidatePrincipalContext context) event handler, If the token has expired, refresh the token.</p>
  <p>At that time, to regenerate the authentication cookie with the new JWT Token, we set the CookeeValidatePrincipalContext.ShouldRenew property to true as shown below.</p>
  <pre><code>    var identity = new ClaimsIdentity(context.Principal.Identity);
      var sid = identity.Claims.FirstOrDefault(x =&gt; x.Type == ClaimTypes.Sid);
      identity.RemoveClaim(sid);
      identity.AddClaim(new Claim(ClaimTypes.Sid, newJwtToken));
      var newPrincipal = new ClaimsPrincipal(identity);
      context.ReplacePrincipal(newPrincipal);
      context.ShouldRenew = true;
  </code></pre>
  <p>As a result, 30 minutes after login, the AntiForgeryRequestToken held by the browser being invalid, and a POST using this RequestToken will result in a 400 Bad Request.</p>
  <p>I would like to know the correct way to combine JWT Token and AntiForgery.
  Thank you.</p>
  <p><strong>Update:</strong>
  Until this JWT Token times out, ajax-posts with this AntiForgeryReqeuestToken will be accepted successfully.</p>
  <p>Twenty minutes after logging in I click the &quot;Update&quot; button and it works correctly.</p>
  <p>If I stay on the same screen and one minute later (i.e., 21 minutes after logging in) I push the &quot;Update&quot; button again, it still works correctly.</p>
  <p>Repeat that and 30 minutes after logging in I push the button and I get a 400 Bad Request.</p>
  <p>Here are some other code samples:</p>
  <p>cshtml code:</p>
  <pre><code>@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
  @{
  var xsrf = Xsrf.GetTokens(ViewContext.HttpContext); // GetAndStoreTokens are already called in a login page.
  }
  
  const ret = await $.post(
      '@Url.Action(&quot;Update&quot;)',
      {
          'id': 1234,
          'data1': &quot;abc&quot;,
          '@(xsrf.FormFieldName)': '@(xsrf.RequestToken)'
      }
  ).promise();
  </code></pre>
  <p>ConfigureServices.cs:</p>
  <pre><code>services.AddScoped&lt;CookieAuthenticationEventHandler&gt;();
  services
      .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
      .AddCookie(x =&gt; {
          x.LoginPath = &quot;/Home&quot;;
          x.AccessDeniedPath = &quot;/Home&quot;;
          x.LogoutPath = &quot;/Signout&quot;;
          x.EventsType = typeof(CookieAuthenticationEventHandler);
          x.ExpireTimeSpan = timeout;
          x.SlidingExpiration = true; 
      });
  </code></pre>
  <p>SigninController.SignIn(signinModel):</p>
  <pre><code>/* Check ID and Password */
  var jwtToken = Authorize(signinModel);
  Claim[] claims = { new Claim(ClaimTypes.Sid, jwtToken), };
  var claimsIdentity = new ClaimsIdentity(
      claims,
      CookieAuthenticationDefaults.AuthenticationScheme
  );
  var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
  var timeout = config.GetValue&lt;TimeSpan&gt;(&quot;Timeout&quot;);
  await HttpContext.SignInAsync(
      CookieAuthenticationDefaults.AuthenticationScheme,
      claimsPrincipal
  );
  HttpContext.User = claimsPrincipal;
  </code></pre>
  <p>the code creating a JWT Token( in the Authorize method):</p>
  <pre><code>public string CreateToken(IEnumerable&lt;Claim&gt; claims) {
  
      var timeStamp = DateTime.Now;
      var timeout = new TimeSpan(&quot;0.00:30:00&quot;);
      var token = new JwtSecurityToken(
          &quot;https://unique-url&quot;,
          &quot;https://unique-url&quot;,
          claims,
          timeStamp,
          expires: DateTime.Now.Add(timeout),
          signingCredentials: SigningCredentials
      );
  
      return new JwtSecurityTokenHandler().WriteToken(token);
  }
  </code></pre>
  <p>CookieAuthenticationEventHandler:</p>
  <pre><code>public override async Task ValidatePrincipal(CookieValidatePrincipalContext context) {
      if(!await Validate(context)) {
          context.RejectPrincipal();
          await context.HttpContext.SignOutAsync();
      }
  }
  
  public async Task&lt;bool&gt; Validate(CookieValidatePrincipalContext context) {
  
      var jwtToken = context.Principal.Claims?.FirstOrDefault(x =&gt; x.Type == ClaimTypes.Sid)?.Value;
      var valid = await ValidatetokenAsync(jwtToken);
  
      if(valid) {
          return true;
      }
  
      var newJwtToken = await RefreshtokenAsync(jwtToken);
      if(string.IsNullOrEmpty(newJwtToken)) {
          return false;
      }
  
      var identity = new ClaimsIdentity(context.Principal.Identity);
      var sid = identity.Claims.FirstOrDefault(x =&gt; x.Type == ClaimTypes.Sid);
      identity.RemoveClaim(sid);
      identity.AddClaim(new Claim(ClaimTypes.Sid, newJwtToken));
      var newPrincipal = new ClaimsPrincipal(identity);
      context.ReplacePrincipal(newPrincipal);
      context.ShouldRenew = true;
  
      return true;
  }
  </code></pre>
  <p><strong>Update 2:</strong></p>
  <p>The root causes of this problem:</p>
  <p>(1) The ClaimsPrincipal passed to HttpContext.SingInAsync contains a JWT Token.</p>
  <p>(2) The expiration date of the login session is different from the expiration date of the JWT Token. The expiration date of the login session is extended each time it is accessed, but the JWT Token is refreshed when it expires.</p>
  <p>(3) When the JWT Token expires and the token is refreshed, the ClaimsPrincipal of the HttpContext must also be updated.</p>
  <p>(4) Because AntiForgery performs validation that depends on this ClaimsPrincipal, any AntiForgeryToken obtained before the JWT Token is refreshed will (suddenly) become invalid.</p>
  <p>(5) Therefore, if HTTP-POST is performed when the JWT Token expires, AntiForgery will fail.</p>
  <p>If this method is wrong, I would like to know the correct method.
  If this method is not wrong, please let me know how to work around it.</p>