Quantcast
Viewing latest article 18
Browse Latest Browse All 42

Answer by Hamfri for How to add Authorization Header to Angular http request?

The following example would fit a situation where you only want some headers added only when accessing resources that require authorization see code below. Kindly note that you need create the getToken method in your authentication.service.ts.

import { Injectable } from '@angular/core';import {  HttpInterceptor,  HttpRequest,  HttpHandler,  HttpEvent} from '@angular/common/http';import { Observable } from 'rxjs';import { environment } from '../../environments/environment';import { AuthenticationService } from '../services/authentication.service';@Injectable({  providedIn: 'root'})export class AuthenticationInterceptorService implements HttpInterceptor {  constructor(public authenticationService: AuthenticationService) {}  intercept(    request: HttpRequest<any>,    next: HttpHandler  ): Observable<HttpEvent<any>> {    const accessToken: string = this.authenticationService.getToken();    // set global application headers.    request = request.clone({      setHeaders: {'Content-Type': 'application/json; charset=utf-8',        Accept: 'application/json','X-AppName': environment.xAppName,'X-Locale': 'en'      }    });    // Set headers for requests that require authorization.    if (accessToken) {      const authenticatedRequest = request.clone({        headers: request.headers.set('Authorization',          `Token token=${accessToken}`        )      });      // Request with authorization headers      return next.handle(authenticatedRequest);    } else {      // Request without authorization header      return next.handle(request);    }  }}

Register the interceptor in app.module.ts as show below:

import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core';import { AuthenticationInterceptorService } from './services/authentication-interceptor.service';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';@NgModule({  declarations: [AppComponent],  imports: [BrowserModule, AppRoutingModule, HttpClientModule],  providers: [    {      provide: HTTP_INTERCEPTORS,      useClass: AuthenticationInterceptorService,      multi: true    }  ],  bootstrap: [AppComponent]})export class AppModule {}

Viewing latest article 18
Browse Latest Browse All 42

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>