How to send JWT automatically in Angular HTTP requests

Using HTTP interceptors to automatically include JWT

Angular is a capable framework for developing highly scalable and enterprise-ready applications. It integrates many features like templating, testing support, animations, routing and HTTP requesting. As many APIs require the requester to be authenticated, the client has to send some kind of token which the backend can verify.

JWT (JSON Web Tokens) are an open, industry standard method for representing claims securely between two parties. They contain JSON-encoded data. This means you can have your JWT store as much JSON data as you want, and you can decode your token string into a JSON object. This makes them convenient for embedding information.

We will use the HttpClient to make authenticated HTTP requests. Since Angular supports HTTP interceptors (since version 4.3), we can modify a request automatically before it is sent to the backend. In this tutorial, I will use an existing library (developed by the experts at Auth0) to automatically include the JWT for every request so we do not need to write an HTTP interceptor ourselves. Please note that this does not apply to the deprecated Http service but only HttpClient since the deprecated Http does not support HTTP interceptors.

How to send JWT in every HTTP request in Angular

Install the angular-jwt library using NPM: npm install @auth0/angular-jwt . Alternatively, create a HTTP interceptor yourself. In your AppModule, you need to provide the way for the interceptor to retrieve the JWT. This should enable the HttpClient to get the JWT and include it in every request. Usually, you store the token either in a cookie (preferred) or in the browser storage. Import the HttpClientModule in your module. This is required in order to inject the HttpClient service in a component/service/pipe/directive. Use the HttpClient to send HTTP requests which will now include the JWT automatically.

A sample AppModule which imports the necessary modules

// called on every request to retrieve the token

export function jwtOptionsFactory(tokenService: TokenService) {

return {

tokenGetter: () => tokenService.getToken(),

whitelistedDomains: ['my-domain', 'my-domain2']

};

}

// the actual module imports

@NgModule({

declarations: [...],

imports: [HttpClientModule, JwtModule.forRoot({

jwtOptionsProvider: {

provide: JWT_OPTIONS,

useFactory: jwtOptionsFactory,

deps: [TokenService]

}

}),

providers: [TokenService, ...]

}

Here is a sample service which uses the HttpClient to make a POST request creating a user.



export class UserService { @Injectable ({providedIn: 'root'})export class UserService { constructor(private httpClient: HttpClient) {} createUser(route: string, body: User) {

return this.httpClient.post(route, body);

}



}

Conclusion

Thanks for reading this article. As you can see, it is easy to automatically send JWT on every HTTP request. If you need more custom behavior and functionality, you can simply write your own HTTP interceptor which Angular supports. Let me know in the comments if this article helped you.

Further recommended articles about JWT