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

Tutorial: 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.

An RxJS BehaviorSubject is used in the Angular tutorial to store the current authenticated user state in  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 the 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 provider’s 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 online 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 { }

Conclusion

I hope the Angular – HTTP Interceptor to Set Auth Header for API Requests if User Logged In Solution would be useful for you to learn something new from this solution. If it helped you then don’t forget to bookmark our site for more Quiz Answers and solutions.

check out on stack overflow

Leave a Reply

Your email address will not be published.

error: Content is protected !!