title: Angular - How to refresh a JWT token using an Authentication Interceptor
body: <p>When a user logs in they get  token_a. To make any API requests in the application they need  token_b. token_b is generated using token_a.</p>
  
  <p>I have built an authentication interceptor which appends token_b to the header of all subsequent api calls after a user logs in. However, token_b has a short expiry time on it and therefore token_b must be regenerated if it is expired.</p>
  
  <p><strong>auth.interceptor.ts</strong></p>
  
  <pre><code>import { Injectable } from '@angular/core';
  import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse, HttpClient, HttpBackend } from '@angular/common/http';
  import { Observable } from 'rxjs/Observable';
  import 'rxjs/add/operator/do';
  
  import { AuthService } from './../services/auth/auth.service';
  import { JwtService } from './../services/jwt/jwt.service';
  
  @Injectable()
  export class AuthInterceptor implements HttpInterceptor {
  
      private httpClient: HttpClient;
  
      constructor(private auth: AuthService, private jwt: JwtService, private http: HttpBackend) {
          this.httpClient = new HttpClient(http);
      }
  
      setHeader(req) {
  
          const authToken = this.auth.getProfileToken();
  
          const authReq = req.clone({
              headers: req.headers.set('Authorization', 'Bearer ' + authToken)
          });
  
          return authReq;
      }
  
      intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler) {
  
          const InterceptorSkipHeader = 'X-Skip-Interceptor';
  
          if (req.headers.has(InterceptorSkipHeader)) {
              const headers = req.headers.delete(InterceptorSkipHeader);
              return next.handle(req.clone({ headers }));
          }
  
          if (this.auth.hasProfileToken() &amp;&amp; this.auth.isProfileTokenExpired()) {
  
              const result = this.refreshToken();
              const ar = this.setHeader(req);
              return next.handle(ar);
          }
  
          const authReq = this.setHeader(req);
          return next.handle(authReq);
  
      }
  
  
      async refreshToken() {
  
          const token = localStorage.getItem('token');
  
          return await this.httpClient.post('//api/v1/users/login', { 'token': token })
              .subscribe((res: any) =&gt; {
                  localStorage.setItem('profile_token', res.token);
                  return res;
              });
  
      }
  
  }
  </code></pre>
  
  <p>In the interceptor function i check to see if the profileToken (token_b) exists and if its expired. if it is i attempt to call refreshToken which sets the new token.</p>
  
  <p>However im finding the refreshToken is not finishing before the interceptor passes on the request.</p>