Overview
TheauthInterceptor is an Angular HTTP interceptor that automatically adds JWT authentication tokens to outgoing HTTP requests. It retrieves the token from local storage via the TokenStorageService and injects it into the Authorization header of each request.
This interceptor uses Angular’s functional interceptor API (
HttpInterceptorFn) introduced in Angular 15+, which is simpler and more tree-shakeable than the class-based approach.Signature
Type Definition
req- The outgoing HTTP request to be interceptednext- The next handler in the interceptor chain
Observable of the HTTP event stream
Implementation
How It Works
- Inject TokenStorageService: Uses Angular’s
inject()function to get the token storage service instance - Retrieve Token: Calls
getToken()to fetch the JWT token from local storage - Check Token Existence: If no token exists, passes the original request unchanged to the next handler
- Clone Request: Creates a cloned request with the
Authorizationheader added - Forward Request: Passes the modified request to the next handler in the chain
The interceptor clones the request rather than modifying it directly because HTTP requests are immutable in Angular. This ensures the original request object remains unchanged.
Dependencies
TokenStorageService
The interceptor depends on theTokenStorageService to retrieve the authentication token:
getToken() method returns the JWT token stored in localStorage under the key 'auth-token', or null if no token exists.
Registration
The interceptor must be registered in your application configuration using theprovideHttpClient() function with the withInterceptors() feature.
app.config.ts
The
withInterceptors() function accepts an array of interceptors that will be applied in the order they are provided. The authInterceptor is applied to all HTTP requests made through Angular’s HttpClient.Usage Examples
Basic Usage
Once registered, the interceptor automatically applies to all HTTP requests:Request Transformation
Before Interceptor:Authentication Flow
After calling
tokenStorage.saveToken(), all subsequent HTTP requests will automatically include the Authorization header. After calling tokenStorage.signOut(), the header will no longer be added.Skipping the Interceptor
If you need to make requests without the authentication token (e.g., public endpoints), you can check the token before the request or use a different HTTP client instance. However, the current implementation safely handles missing tokens by passing the request unchanged.Testing
The interceptor can be tested using Angular’sTestBed:
Related Documentation
- TokenStorageService - Service for managing JWT tokens
- HttpClient - Angular’s HTTP client service
- AuthService - Authentication service
Source Code
Location:src/app/core/interceptors/auth-interceptor.ts
View the complete implementation in the source repository.