Automatically Add Auth Token to HTTP Requests
If your backend service requires the auth token for authorization, you can include it in every HTTP request.
Angular
Implement Angular's HttpInterceptor
class, attaching the auth token to the authorization header.
_42import { Injectable } from '@angular/core';_42import { from, Observable } from 'rxjs';_42import { flatMap } from 'rxjs/operators';_42import {_42 HttpEvent,_42 HttpInterceptor,_42 HttpHandler,_42 HttpRequest,_42} from '@angular/common/http';_42_42import { IdentityService } from '../identity';_42_42@Injectable()_42export class AuthInterceptor implements HttpInterceptor {_42 constructor(private identity: IdentityService) {}_42_42 intercept(_42 req: HttpRequest<any>,_42 next: HttpHandler,_42 ): Observable<HttpEvent<any>> {_42 return from(_42 this.requestRequiresToken(req)_42 ? this.identity_42 .getToken()_42 .then(token => {_42 if (token) {_42 req = req.clone({_42 setHeaders: {_42 Authorization: 'Bearer ' + token,_42 },_42 });_42 }_42 })_42 .catch(() => Promise.resolve())_42 : Promise.resolve(),_42 ).pipe(flatMap(() => next.handle(req)));_42 }_42_42 private requestRequiresToken(req: HttpRequest<any>): boolean {_42 return !/\/login$/.test(req.url);_42 }_42}