Angular HTTP Interceptor for Token šŸ”

beginner
17 min

Angular HTTP Interceptor for Token šŸ”

Welcome to our comprehensive guide on using Angular's HTTP Interceptor for managing authentication tokens! By the end of this lesson, you'll have a solid understanding of how to secure your Angular applications by protecting API calls with authentication tokens. šŸŽÆ

What is an HTTP Interceptor? šŸ“

An HTTP Interceptor is a way to intercept HTTP requests and responses in Angular. It allows you to modify the outgoing requests and incoming responses for various purposes, such as adding headers, modifying the data, or handling errors.

Why use an HTTP Interceptor for Tokens? šŸ’”

In applications that require authentication, it's common to include an access token in the HTTP headers of requests to secure API calls. Using an HTTP Interceptor for managing these tokens ensures that the token is always included in outgoing requests and refreshed when necessary, making your application more secure.

Setting Up an HTTP Interceptor āœ…

Step 1: Create an Interceptor

To create an interceptor, you'll need to implement the Interceptor interface and provide it in the app's providers array.

typescript
import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'; @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler) { // Your interception logic goes here } }

Step 2: Add the Interceptor to the Providers

Add the interceptor to the app's root module's providers array:

typescript
import { AuthInterceptor } from './auth.interceptor'; @NgModule({ providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } ], // ... }) export class AppModule { }

Step 3: Implement Interception Logic

Now, you can implement the interception logic in the AuthInterceptor class to modify the outgoing requests and handle responses.

typescript
import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { finalize } from 'rxjs/operators'; const TOKEN_KEY = 'auth-token'; @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const token = localStorage.getItem(TOKEN_KEY) || ''; // If the request is not to the authentication service, add the token to the headers if (req.url.indexOf('/api') > -1 && req.url.indexOf('/auth') === -1) { const authReq = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }); return next.handle(authReq).pipe( finalize(() => { // Clear the token from the cache on every request to prevent session hijacking localStorage.removeItem(TOKEN_KEY); }) ); } // For authentication requests, return the next request handler to handle the request normally return next.handle(req); } }

Quiz šŸ“

Quick Quiz
Question 1 of 1

What is an HTTP Interceptor used for in Angular?

Wrapping Up

By implementing an HTTP Interceptor for managing authentication tokens, you've made your Angular application more secure and ensured that API calls are always protected with valid access tokens. Keep up the good work, and happy coding! šŸŽ‰

Remember, practice is key to mastering this concept, so feel free to create your own interceptors for various purposes and experiment with different interception strategies.

šŸ’” Pro Tip: Consider implementing a refresh token strategy to ensure that the access token is always up-to-date and available when needed. šŸ“ Note: This will help your application remain secure even when the access token expires.