Interceptor using Access Token then Refresh Token Angular 2
Interceptor using Access Token then Refresh Token
2021
import { Injectable } from '@angular/core';import {HttpRequest,HttpHandler,HttpEvent,HttpInterceptor,HttpErrorResponse,} from '@angular/common/http';import { Router } from '@angular/router';import { Observable, of, throwError } from 'rxjs';import {concatMap,delay,retryWhen,finalize,switchMap,catchError,} from 'rxjs/operators';import { LoadingService } from '../shared/services/loading.service';import { ApiService } from '../shared/services/api.service';@Injectable()export class AuthInterceptor implements HttpInterceptor {private retry = {count: 1,delay: 1000,status: [408, 429, 500, 502, 503, 504],};constructor(private router: Router,private api: ApiService,private loading: LoadingService,) { }intercept(request: HttpRequest<unknown>,next: HttpHandler): Observable<HttpEvent<unknown>> {if (this.accessToken) {request = this.addToken(request, this.accessToken);}return next.handle(request).pipe(retryWhen((error) =>// Retry requesterror.pipe(concatMap((err, count) => this.retryContent(err, count)),delay(this.retry.delay))),catchError((error) => {// HttpErrorResponseif (error instanceof HttpErrorResponse) {if (error.status === 401) {if (this.refreshToken !== 'undefined') {// POST refreshTokenreturn this.api.post(`/refreshToken`, {refreshToken: this.refreshToken,}).pipe(switchMap((res) => {// Update localStoragelocalStorage.clear();localStorage.setItem('accessToken', res.accessToken);localStorage.setItem('refreshToken', res.refreshToken);localStorage.setItem('expiredIn', res.expiredIn); // 1617639398768 (new Date().getTime())request = this.addToken(request, res.accessToken);return next.handle(request);}),catchError((err) => {// HttpErrorResponseif (err instanceof HttpErrorResponse) {if (err.status === 401) {this.router.navigate(['login']);} else {this.expireTimeRedirectToErrPage();}}return throwError(err);})).toPromise();} else {return throwError(error);}} else {return throwError(error);}}}),finalize(() => {this.loading.off();}));}private get accessToken(): string {return localStorage.getItem('accessToken');}private get refreshToken(): string {return localStorage.getItem('refreshToken');}private get expiredIn(): number {return Number(localStorage.getItem('expiredIn'));}private addToken(request: HttpRequest<any>,token: string): HttpRequest<unknown> {return request.clone({headers: request.headers.set('accessToken', `bearer ${token}`),});}private retryContent(error, count): Observable<any> {if (count < this.retry.count &&this.retry.status.find((f) => f === error.status)) {return of(error);}return throwError(error);}private expireTimeRedirectToErrPage(): void {if (Date.now() >= this.expiredIn) {this.router.navigate(['error']);}}}
0 nhận xét:
Post a Comment