In this article, I will show you how to integrate the refresh token mechanism to the ASP.NET Zero project.

We use Angular HttpInterceptor to handle requests. And I will implement how to use refresh tokens using Interceptor.

As a summary, the HttpInterceptor works as a middleware between each requests and server. As a default, all your requests enter the HttpInterceptor’s intercept method. And then you can handle the request and release it to the next handler. Our interceptor will work as shown in the below diagram.

img

Before each request:

  • Handle request(add auth header etc.) and call server with that request. And subscribe to result.

After getting a response:

  • Check if it is a HTTP 401(unauthorized) result
  • If it is not, pass it to next handler
  • If it is HTTP 401:
  • Check whether if there is an ongoing reauthentication with the refresh token process.
  • If there is, store requests and wait for the auth result.
  • Else, try to authenticate with refresh token (If refresh token exists)
  • If you can auth with a refresh token, store new tokens
  • Call previous requests which you have got HTTP 401 error.
  • If there are any stored requests call them with new auth token.

Implementation

We use the abp-ng2-module package in Angular projects. It has basic implementations that we may need while developing our Angular projects. We use Angular HttpInterceptorto handle requests (adding our headers, handling errors, etc…) and it’s located in the abp-ng2-modulepackage.

Check it out on GitHub: https://github.com/aspnetboilerplate/abp-ng2-module/blob/master/projects/abp-ng2-module/src/lib/interceptors/abpHttpInterceptor.ts

We use that interceptor in the ASP.NET Zero project.

Let’s start coding.

Since we have two seperate projects and our interceptor don’t know about a client I create abstract service which responsible for authorization with refresh token (if it exists).

Our interceptor was as seen below

What we need to do is; catch errors on requests and handle it, so we can change the intercept method as seen below

aspnetboilerplate/abp-ng2-module/abpHttpInterceptor.tsTake a look at all the codes in interceptorgithub.com

The abp-ng2-module package is now ready to use with the refresh token. Time to update ASP.NET Zero.

I updated abp-ng2-module packages on zero and created a service called ‘ZeroRefreshTokenService’ at the relevant location.

Finally, I have added my token service to the providers of my module.

@NgModule({
   ...
   providers:[
      ...
      { provide: RefreshTokenService, useClass: ZeroRefreshTokenService}
   ]
})

As you see below, GetEditionComboboxItem , GetTenants actions are called and we get HTTP401 unauthorized results, then our interceptor calls RefreshTokenaction and successfully gets the new token. Then it recalls all the unauthorizated requests with the new token.

img