Angular: Using HTTPInterceptor for token refreshing

Anthony Monkov
3 min readJun 9, 2018

--

Nowadays web applications don’t secure only with access token, today authentication process includes much more complicated parts. Like refresh token.

What is refresh token?

Refresh token can reload a couple of refresh(itself) and access tokens when the last has been expired.

This kind of tokens is for a situation when someone steals an access token and we should prevent him from using it for a long time. Today access token has a very small lifecycle, that is about half an hour. Refresh token can be used only once. Just one access token for one refresh token.

Example of tokens refreshing

What is our aim?

We should make token refreshing invisible for usual user, in other words: our aim is to hide token refreshing process from ui. In this tutorial we will use HTTPInterceptor to rich this scopes.

How interceptors works

If we imagine how inceptor will look like: it’s a filter of requests and responses.

Interceptor example

We use inceptor for adding access token for every request. You can read about this topic here. But in our story we shouldn’t add something for request. Our task is filtering response from server, handle errors and do some stuff. Well, let’s start.

Let’s code!

Firstly if you don’t have http interceptor yet, we’re gona generate it via ng command:

ng generate interceptor AuthInterceptor

Angular will generate auth-interceptor.ts file. Probably it should seem something like this.

Next step, it’s be better if we import our interceptor to ngModule, providers in app.module.ts. You can do it this way:

And now, the most interesting part. Well, I added some points of work with access token to our example, actually — cloning request add authentication header and send it to the server with errors catching.

After that we need tocatch authentification error, when token expired. As for me it looks like this:

{status: 401, message: “Token is exp”}

Let’s catch it!

Finally we should reload refresh token, for this we need to add HttpClient module. And don’t forget to import mergeMap from RxJS. Well, write some lines of code…

After sending reload request we can catch one more error and do some stuff with it.

Good job! We’ve done it! Now our interceptor could refresh tokens and retry fieled request. Here you can see full code:

Thank you for reading!

--

--