Adding Authorization Header to HTTP Request in Angular 4 and 5

When a JWT token is sent to the backend, it is expected to be in the authorization header of the HTTP request. The token itself is signed with a salt by a trusted source and usually contains referential data such as userId which would then be used in user-specific backend operations. The most common approach for adding an authorization header to an HTTP request in Angular is creating an interceptor class and having the interceptor make modifications to the requests.

As of Angular 4, you can create an HTTP interceptor that intercepts all HTTP requests and modifies them to include additional HTTP headers. To get started, create an Angular service and have it implement the HttpInterceptor.

ng g service interceptors/auth

Add the following code to the service :

Make sure to add the generated service class to the providers[] in the root module of the application. Then add the inherited intercept() method to the service class.

Clone the request that gets passed to the intercept() method and add your additional headers. Then invoke next.handle(req) which notifies the interceptor to invoke the next operation.

That’s it! You have successfully added an interceptor to your Angular application:).

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store