Skip to content

Instantly share code, notes, and snippets.

@argentinaluiz
Created January 16, 2019 16:51
Show Gist options
  • Save argentinaluiz/26c0e90e48726994fa56d54d219d8b93 to your computer and use it in GitHub Desktop.
Save argentinaluiz/26c0e90e48726994fa56d54d219d8b93 to your computer and use it in GitHub Desktop.
Refresh token with Angular
@NgModule({
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptorService,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: RefreshTokenService,
multi: true
},
],
})
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);
})
);
}
}
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