In this tutorial, we will explore Angular's HTTP Interceptors, and how to utilize them for adding an authentication token to each HTTP request automatically.
By the end of this tutorial, you will be able to create an interceptor service that attaches an authentication token to each request.
HTTP Interceptors in Angular are used to intercept HTTP requests or responses from your application to the server. They allow you to modify, log, or even cancel these requests. They are especially useful for attaching authentication tokens.
To create an interceptor, you can create a service that implements the HttpInterceptor
interface and its intercept
method.
HttpInterceptor
interface.intercept
method.We will create a new service called AuthInterceptor
:
// auth.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpInterceptor } from '@angular/common/http';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler) {
// Clone the request and replace the original headers with
// cloned headers, updated with the authorization.
const authReq = request.clone({
headers: request.headers.set('Authorization', 'Bearer ' + 'your-auth-token')
});
// send cloned request with header to the next handler.
return next.handle(authReq);
}
}
After creating the interceptor, we need to provide it in the app.module.ts
:
// app.module.ts
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth.interceptor';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule { }
In this code, we provide the interceptor service to the HTTP_INTERCEPTORS
injection token, which is an array of all provided interceptors.
In this tutorial, you've learned:
- What HTTP Interceptors are and how they work in Angular.
- How to create an interceptor service to add an authentication token to every HTTP request.
- How to register this interceptor.
Now, you can use this knowledge to handle authentication in your Angular applications more effectively.
AuthInterceptor
to get the token from a separate AuthService
.For further practice, try to use interceptors for other use-cases in your application, such as adding a 'Content-Type' header to all requests, or handling responses globally.
Remember, practice is the key to mastering any concept. Happy coding!