Angular 2 and JWT authentication

Ivan Radunović
Beautiful Angular
Published in
3 min readJan 18, 2017

--

You can pass Authorization headers in couple of ways, solution I presented here is a bit more elaborate cause it could include loading spinner and centralized error handling for each http request.

Extending Http service

First thing to do is to create custom Http service cause we need to pass some headers in each request.

From the code above everything is pretty clear, only new thing is MyCustomRequestOptions class which is injected into constructor.

Appending headers

Usual way of doing JWT authentication is by passing Authorization header with the actual token. There are other ways like passing the token via query parameter but then we wouldn’t need headers.

To be able to pass custom headers to http service we need to extend BaseRequestOptions class.

From constructor you can see that I am calling superclass constructor first and after that I am extracting value of token from local storage.

You can get that value however you want in my case I stored user object in local storage and it posses JWT token.

Back to custom Http service

Now I need to overwrite each http method that I am going to use, that is the place to display some spinner to the user and do error handling.

For this example I took get method, I am also using few helper methods for full url and request options.

I will import this service into CoreModule, cause it extends built-in class it needs to have service provider defined and factory:

Factory

I am storing my factories inside _factories directory:

Closing

The only thing left now is importing CoreModule into AppModule.

Source code

Entire source code is published on GitHub.

--

--