Using Interceptors for Authentication

Tutorial 4 of 5

Using Interceptors for Authentication in Angular

1. Introduction

Goal of the Tutorial

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.

Learning Outcomes

By the end of this tutorial, you will be able to create an interceptor service that attaches an authentication token to each request.

Prerequisites

  • Basic understanding of TypeScript and Angular.
  • Installed Angular CLI on your system.
  • Basic knowledge of HTTP requests and REST APIs.

2. Step-by-Step Guide

HTTP Interceptors

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.

Creating an Interceptor

To create an interceptor, you can create a service that implements the HttpInterceptor interface and its intercept method.

Step-by-Step Guide

  • Generate a new service using the Angular CLI.
  • Implement the HttpInterceptor interface.
  • Override the intercept method.
  • Use the clone method to clone the request and add a new "Authorization" header.
  • Register the interceptor in the app.module.ts file.

3. Code Examples

Creating the Interceptor Service

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);
  }
}

Registering the Interceptor

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.

4. Summary

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.

5. Practice Exercises

  1. Create an interceptor that logs all HTTP requests and responses.
  2. Create an interceptor that catches HTTP errors and displays an alert with the error message.
  3. Modify the 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!