Tel Map


Angular 5 HttpInterceptor – Add Bearer Token to HttpClient Requests

Der Inhalt wird unten in einer verfügbaren Sprache angezeigt. Klicken Sie auf den Link, um die aktuelle Sprache zu ändern.

In this article I will describe how to add a Http Authentication Bearer token to each request done from Angular via HttpClient by implementing a Angular 5 HttpInterceptor. This way the bearer token has not be added to each request separately while doing Ajax request e.g. to a REST api. This is for example useful, if you have some api that is protected by OAuth and you have to sent a JWT token in order to get access.


Here is the code for the HttpInterceptor itself. It has to implement the HttpInterceptor interface and therefore provide an implementation for the intercept method.

A couple of things to notice here. Since I’m working with async / await and I use Promises in my code and the intercept method returns an Observable, I have to convert my Promise to an Observable using the Observable.fromPromise method.

In the handleAccess method I get my access token from my msalService. This is a service for handling login / access etc. using Microsoft Authentication Library for JavaScript (In my case Azure AD B2C).

The next step is to actually add the token to the HttpClient request.

Immutable Request / RequestHeader

One very important point is, that you cannot simply set or add new headers to the request object.

The request and header objects are immutable. Even if you change something by adding a new header or trying to set some header, this will not work. This took me a while to figure out, because the api of these objects allows you to do so. But the changes you make are then not reflected in the requests you make later on.

So the solution is to copy / clone the original objects and do the changes there (see code above)

Add CustomHttpInterceptor to @NgModule

So the only thing left to do is to register the new CustomHttpInterceptor, so that it will be used from now on.

That’s it!

So this article demonstrates how to add a custom authorization header to all HttpClient request in Angular 5. Similarly you could e.g. add code to do a redirect to a login page here in case you get a 401 (unauthorized) from the REST api.

I hope this article helps some people save some time I wasted because of the immutable object request header.

If you have any questions etc…. leave a comment below.

Eine Antwort auf „Angular 5 HttpInterceptor – Add Bearer Token to HttpClient Requests“

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.