Created
January 16, 2019 16:51
-
-
Save argentinaluiz/26c0e90e48726994fa56d54d219d8b93 to your computer and use it in GitHub Desktop.
Refresh token with Angular
This file contains hidden or 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
@NgModule({ | |
providers: [ | |
{ | |
provide: HTTP_INTERCEPTORS, | |
useClass: TokenInterceptorService, | |
multi: true | |
}, | |
{ | |
provide: HTTP_INTERCEPTORS, | |
useClass: RefreshTokenService, | |
multi: true | |
}, | |
], | |
}) |
This file contains hidden or 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 { | |
HttpClient, | |
HttpErrorResponse, | |
HttpEvent, | |
HttpHandler, | |
HttpInterceptor, | |
HttpRequest | |
} from "@angular/common/http"; | |
import {Observable, throwError} from "rxjs"; | |
import {catchError, flatMap, tap} from "rxjs/operators"; | |
import {TokenInterceptorService} from "./token-interceptor.service"; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class RefreshTokenService implements HttpInterceptor { | |
constructor(private http: HttpClient, private tokenInterceptor: TokenInterceptorService) { | |
} | |
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
return next.handle(req) | |
.pipe( | |
catchError(error => { | |
const responseError = error as HttpErrorResponse; | |
if (responseError.status === 401) { | |
return this.http.post<any>('http://localhost:8000/api/refresh', {}) | |
.pipe( | |
tap(response => localStorage.setItem('token', response.token)), | |
flatMap(() => this.tokenInterceptor.intercept(req, next)) | |
); | |
} | |
return throwError(error); | |
}) | |
); | |
} | |
} |
This file contains hidden or 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 {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http"; | |
import {Observable} from "rxjs"; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class TokenInterceptorService implements HttpInterceptor { | |
constructor() { | |
} | |
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
const tokenizedReq = req.clone({ | |
setHeaders: { | |
Authorization: 'Bearer ' + localStorage.getItem('token') | |
} | |
}); | |
return next.handle(tokenizedReq); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment