title: How can I ensure a token doesn't expire between preflight calls?
body: <p>I'm facing an intermittent problem with Keycloak. If a user triggers a preflight API call and Keycloak's token expires between that and the actual API call, the preflight call will return a 200, but the real API call will return a 401 (as the token has now expired).</p>
  
  <p>The flow of events is essentially:</p>
  
  <ol>
  <li>User triggers preflight API call, generating an OPTIONS request.</li>
  <li>Keycloak's token expires and is refreshed.</li>
  <li>Preflight request returns, GET call is sent out with old Keycloak token.</li>
  <li>The API returns a 401 as the old token has expired.</li>
  </ol>
  
  <p>Here is what it looks like in my browser's Network tab:</p>
  
  <p><img src="https://i.stack.imgur.com/qzvzm.png" alt="Example Network tab flow"></p>
  
  <p>How can I ensure the Keycloak token doesn't expire between these events?</p>
  
  <p>Here's the code I'm using:</p>
  
  <pre class="lang-js prettyprint-override"><code>async onTokenExpired() {
    this.token = await this.updateToken();
    this.updateHeaders();
  }
  
  updateHeaders() {
    http.setHeaders({
      Authorization: `Bearer ${this.token}`
    });
  }
  
  updateToken() {
    return new Promise((resolve, reject) =&gt; {
      this.keycloak.updateToken()
        .success(() =&gt; {
          resolve(this.keycloak.token);
        })
        .error(reject);
    });
  }
  </code></pre>