Created
November 9, 2020 21:52
-
-
Save blogcacanid/083ee9995db49f4643bfd077d45fd475 to your computer and use it in GitHub Desktop.
auth.interceptor.ts Authentication JWT Angular 9 Lumen 7
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 { HTTP_INTERCEPTORS } from '@angular/common/http'; | |
import { Injectable } from '@angular/core'; | |
import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'; | |
import { TokenStorageService } from '../_services/token-storage.service'; | |
// for Lumen 7 back-end | |
const TOKEN_HEADER_KEY = 'Authorization'; | |
// for Node.js Express back-end | |
// const TOKEN_HEADER_KEY = 'x-access-token'; | |
@Injectable() | |
export class AuthInterceptor implements HttpInterceptor { | |
constructor(private token: TokenStorageService) { } | |
intercept(req: HttpRequest<any>, next: HttpHandler) { | |
let authReq = req; | |
const token = this.token.getToken(); | |
if (token != null) { | |
// for Lumen 7 back-end | |
authReq = req.clone({ headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token) }); | |
// for Node.js Express back-end | |
// authReq = req.clone({ headers: req.headers.set(TOKEN_HEADER_KEY, token) }); | |
} | |
return next.handle(authReq); | |
} | |
} | |
export const authInterceptorProviders = [ | |
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment