Token Based Security: Angular Applications – Part 3

Introduction

In previous post of this series, we configured our Angular application as a client of IdnentityServer and completed the login/logout process.

However even though user was logged-in, the REST API calls were still not authorized:

In this post, we will authorize HTTP calls by passing bearer token as an Authorization Header.

Now, if you are new to token-based security or how we setup the Angular application, I will suggest to first go through few previous posts and then the topics in this post will much easier to follow. Let’s see how to get an Access Token, next.

Get Access Token

I’ve added following method to authService (we created this service in previous post) to get the access token:

Next, we will build a service based on Http Intercepter, which will call this method to get the access-token and then further use this access-token to set HTTP Headers for calls to the protected API.

Authorizing REST API Calls

We can add bearer token to HTTP requests manually or can use HTTP Interceptor in the pipeline to do this automatically.

Here is the boiler plate code for such a service:

I’ll not go into the details of HttpInterceptor, and by the way I used Angular Snipped extension for VS-Code to quickly create the template code. You can install this extension and it will help you quickly write code for various purposes:

Setting Up HTTP Interceptor

Let’s update the of the HttpInterceptor to set header with bearer token:

The code is very boiler plate. we are calling the getAccessToken() method which we created earlier in AuthService. Then we just set the retrieved bearer token on HTTP Header. To return an observable we first used to toPromise function and wrap the code in an rxjs from operator.

Now, any HTTP Call from the angular application will pass through this interception point and token will be added automatically.

We also need to register this intercepter to the application as shown below:

Testing the Application

With all these changes in-place, lets run the applications (IdentityServer, ResourceAPI and Anglar client) and visit the Products List page again and this time HTTP Request is authorized and data is retrieved and shown on UI:

Excluding Bearer Token when Needed

There might be situations, when for some HTTP calls (may be those to a different API), may be you don’t want to set the bearer token automatically, or may be a different bearer-token etc. One way to do that, is to just introduce a simple check as shown below:

Now, only the call intended for the specific API will have bearer token added automatically.

Summary

In this post, we learned how to authorize HTTP calls to resource API by using an Angular HTTP Interceptor. You can download the source code from this git repository. If you have some comments or questions, let me know. Till next time, Happy Coding.

My Recent Books