Skip to content

Instantly share code, notes, and snippets.

@blogcacanid
Created November 9, 2020 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blogcacanid/083ee9995db49f4643bfd077d45fd475 to your computer and use it in GitHub Desktop.
Save blogcacanid/083ee9995db49f4643bfd077d45fd475 to your computer and use it in GitHub Desktop.
auth.interceptor.ts Authentication JWT Angular 9 Lumen 7
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