Published: September 24 2021

Angular - HTTP Interceptor to Set Auth Header for API Requests if User Logged In

This is a quick example of how to automatically set the HTTP Authorization header for requests sent from an Angular app to an API when the user is authenticated.

The below code snippet is from a Angular Facebook Login tutorial I posted a little while ago, to see the code running in a live demo app check out Angular - Facebook Login Tutorial & Example.

An RxJS BehaviorSubject is used in the Angular tutorial to store the current authenticated user state in the accountService and expose access to its value via the accountValue property, but you can use another way to store the user's logged in state if you prefer such as NgRx. The only requirement is that you can check if the user is logged in from the HTTP interceptor class below (JwtInterceptor).

 

Angular JWT Interceptor

Path: /src/app/_helpers/jwt.interceptor.ts

The JWT Interceptor intercepts HTTP requests from the application to add a JWT auth token to the HTTP Authorization header if the user is logged in and the request is to the Angular app's API URL (environment.apiUrl).

It's implemented using the HttpInterceptor interface included in the HttpClientModule, by implementing the HttpInterceptor interface you can create a custom interceptor to modify http requests before they get sent to the server.

Http interceptors are added to the request pipeline in the providers section of the app.module.ts file.

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';

import { environment } from '@environments/environment';
import { AccountService } from '@app/_services';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    constructor(private accountService: AccountService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add auth header with jwt if account is logged in and request is to the api url
        const account = this.accountService.accountValue;
        const isLoggedIn = account?.token;
        const isApiUrl = request.url.startsWith(environment.apiUrl);
        if (isLoggedIn && isApiUrl) {
            request = request.clone({
                setHeaders: { Authorization: `Bearer ${account.token}` }
            });
        }

        return next.handle(request);
    }
}
 

Angular App Module

Path: /src/app/app.module.ts

This is the AppModule from the Angular Facebook Login tutorial, the app module defines the root module of the angular application along with metadata about the module, for more info see https://angular.io/docs/ts/latest/guide/ngmodule.html.

The JwtInterceptor is added to the HTTP request pipeline for the app on line 31.

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

// used to create fake backend
import { fakeBackendProvider } from './_helpers';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { JwtInterceptor, ErrorInterceptor, appInitializer } from './_helpers';
import { AccountService } from './_services';
import { HomeComponent, EditAccountComponent } from './home';
import { LoginComponent } from './login';

@NgModule({
    imports: [
        BrowserModule,
        ReactiveFormsModule,
        HttpClientModule,
        AppRoutingModule
    ],
    declarations: [
        AppComponent,
        HomeComponent,
        EditAccountComponent,
        LoginComponent
    ],
    providers: [
        { provide: APP_INITIALIZER, useFactory: appInitializer, multi: true, deps: [AccountService] },
        { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
        { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },

        // provider used to create fake backend
        fakeBackendProvider
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

 


Need Some Angular Help?

Search fiverr for freelance Angular developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by