Created
August 24, 2019 08:57
-
-
Save Devstackr8/5068aedc5d6e52c7aab54aff92f42e66 to your computer and use it in GitHub Desktop.
Web Request Interceptor (Auth tokens)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from "@angular/core"; | |
import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse } from '@angular/common/http'; | |
import { Observable, throwError } from 'rxjs'; | |
import { AuthService } from './services/auth.service'; | |
import { catchError, switchMap } from 'rxjs/operators'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class WebRequestInterceptor implements HttpInterceptor { | |
constructor(private authService: AuthService) { } | |
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> { | |
console.log('I am in the intercept method') | |
request = this.attachAccessToken(request); | |
return next.handle(request) | |
.pipe( | |
catchError((error: HttpErrorResponse) => { | |
console.log('I am in CATCH ERROR') | |
console.log(error); | |
if (error.status === 401) { | |
if (error.url.endsWith('/users/me/access-token')) { | |
// the refresh token has expired | |
console.log('REFRESH TOKEN HAS EXPIRED') | |
this.authService.logout(); | |
return throwError(error); | |
} | |
return this.authService.refreshAccessToken() | |
.pipe( | |
switchMap(() => { | |
// the code here will run once the access token | |
// has been refreshed, and the new one is in | |
// localStorage (see: getNewAccessToken()) | |
// so now we want to attach the new access token | |
// to the request object | |
request = this.attachAccessToken(request); | |
// and then return next.handle() with the updated | |
// request object so that it can be re-sent with | |
// the new accessToken | |
return next.handle(request); | |
}) | |
) | |
} | |
return throwError(error); | |
}) | |
) | |
} | |
attachAccessToken(request: HttpRequest<any>) { | |
// get the access token | |
const token = this.authService.getAccessToken(); | |
if (!token) return request; | |
// if the code reaches this point, token has a value | |
// put access token in request headers | |
return request.clone({ | |
setHeaders: { | |
'x-access-token': token | |
} | |
}) | |
// this will return a request obj that is an exact | |
// clone of the one that was passed in | |
// but it will now have the access token in the headers | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment