Skip to main content
Version: 4.2

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.


_42
import { Injectable } from '@angular/core';
_42
import { from, Observable } from 'rxjs';
_42
import { flatMap } from 'rxjs/operators';
_42
import {
_42
HttpEvent,
_42
HttpInterceptor,
_42
HttpHandler,
_42
HttpRequest,
_42
} from '@angular/common/http';
_42
_42
import { IdentityService } from '../identity';
_42
_42
@Injectable()
_42
export 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
}

Contents