Using HttpInterceptor to add a Bearer 🐻 token to API calls with ng-oidc-client

𝐀𝐥𝐞𝐱
2 min readNov 5, 2018

--

Using HttpInterceptor to add a Bearer token to API calls with NG OIDC Client

This is a follow up post of “Securing your Angular 7+ application with OIDC and NgRx”. We’ll be building in this example right on top of the previously created DraftApp. If you want to skip the initialization of the Angular App grab the final code from GitHub and continue right away:
https://github.com/alx-andru/draft

A common reason to obtain an access token is to use the token to get access to restricted information of an API. We’ll be using an HttpInterceptor to add the token to each request we’re sending.

First we have to create a new service TokenInterceptor.

ng g s providers/TokenInterceptor

Which then implements the HttpInterceptor interface.

We’re using the identity$ selector of the OidcFacade. If the user exists and has an Access Token, we’ll clone the request and set the Authorization Headers with the Bearer token.

To enable our interceptor, we have to add it to the list of providers in our AppModule along with the HttpModule.

One of the easiest ways to test it right away is to call the Userinfo Endpoint of the Identity Server. This api call requires an active access_token and as we had to use an Identity Provider to get the token, everything else should be already ready to go.

First we modify our existing HomeComponent to trigger a simple http call and test our TokenInterceptor.

To resolve the correct URL we can get the actual OIDC Client instance through the OidcFacade and read the settings. Obtaining the user is a simple HTTP GET request to the /connect/userinfo endpoint.

Tip: If you’re using Auth0 as an Identity Provider, the userinfo endpoint follows the format: `${identityProviderUrl}/userinfo` , or if you’re using Okta the format will be: `${identityProviderUrl}/oauth2/v1/userinfo`

Tip: Unless it is necessary, you should not blindly apply a bearer token to every single HTTP Request in your entire application. You can easily match the request url like this simplified example:

if (!req.url.match('https://apiEndpointUrl/v1')) {
return next.handle(req);
}

If you’d like to learn more about Interceptors and various ways to use them, check out some of my favourite articles on that topic:

Feel free to leave comments with any questions, feedback or ideas 🙌 …

--

--

𝐀𝐥𝐞𝐱

VP, Engineering at sherpa° — helping travellers around the world navigate complex travel restrictions — bringing visas as ancillary services to airlines