12 March 2021

Interceptor using Access Token then Refresh Token Angular 2

 


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 { ObservableofthrowError } 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: [408429500502503504],
  };

  constructor(
    private routerRouter,
    private apiApiService,
    private loadingLoadingService,
  ) { }

  intercept(
    requestHttpRequest<unknown>,
    nextHttpHandler
  ): Observable<HttpEvent<unknown>> {
    if (this.accessToken) {
      request = this.addToken(requestthis.accessToken);
    }
    return next.handle(request).pipe(
      retryWhen((error=>
        // Retry request
        error.pipe(
          concatMap((errcount=> this.retryContent(errcount)),
          delay(this.retry.delay)
        )
      ),
      catchError((error=> {
        // HttpErrorResponse
        if (error instanceof HttpErrorResponse) {
          if (error.status === 401) {
            if (this.refreshToken !== 'undefined') {
              // POST refreshToken
              return this.api
                .post(`/refreshToken`, {
                  refreshToken: this.refreshToken,
                })
                .pipe(
                  switchMap((res=> {
                    // Update localStorage
                    localStorage.clear();
                    localStorage.setItem('accessToken'res.accessToken);
                    localStorage.setItem('refreshToken'res.refreshToken);
                    localStorage.setItem('expiredIn'res.expiredIn); // 1617639398768 (new Date().getTime())
                    request = this.addToken(requestres.accessToken);
                    return next.handle(request);
                  }),
                  catchError((err=> {
                    // HttpErrorResponse
                    if (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(
    requestHttpRequest<any>,
    tokenstring
  ): HttpRequest<unknown> {
    return request.clone({
      headers: request.headers.set('accessToken'`bearer ${token}`),
    });
  }

  private retryContent(errorcount): 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']);
    }
  }
}


https://devdactic.com/ionic-jwt-refresh-token/

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang