Joseph
Joseph

Reputation: 7755

Making Global Authentication Header For Every Http Request in Angular 4

I want to make the authorization header not to declare it again and again when i get something from the api.

I need to attached authorization headers every time i need to get data from the api. I am currently using HTTPCLIENT in Angular 4. My code:

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';
import { AppSettings } from '../app.constants';


@Injectable()
export class AuthService {
  private loggedIn = false;

  constructor(private httpClient: HttpClient) {
  }

  loginUser(email: string, password: string) {  
    const headers = new HttpHeaders() 
    .set('Content-Type', 'application/json');

    return this.httpClient
    .post(
       GLOBAL_URL.LOGIN_URL + '/auth/login', 
       JSON.stringify({ email, password }), 
       { headers: headers }
    )
    .map(
        (response: any) => {
         localStorage.setItem('auth_token', response.token);
          this.loggedIn = true;
          return response;
        });
   }

    isLoggedIn() {
      if (localStorage.getItem('auth_token')) {
        return this.loggedIn = true;
      }
    }

   logout() {
     localStorage.removeItem('auth_token');
     this.loggedIn = false;
    }

products.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import{ GloablSettings } from '../global.constants';

@Injectable()
export class SettingsService {
    settingslist: any;
    settings: any;

  constructor(private httpClient: HttpClient) {}

  getSettings(){
    if(this.settingslist != null) {
      return Observable.of(this.settingslist);
    } 

    else {
      const authToken = localStorage.getItem('auth_token'); 
      const headers = new HttpHeaders() 
      .set('Content-Type', 'application/json') 
      .set('Authorization', `Bearer ${authToken}`);

      return this.httpClient
        .get(GLOBAL_URL.GET_URL + '/settings/product', { headers: headers })
        .map((response => response))
        .do(settingslist => this.settingslist = settingslist)
        .catch(e => {
            if (e.status === 401) {
                return Observable.throw('Unauthorized');           
            }

        });
    }
  }
}

Upvotes: 2

Views: 2668

Answers (1)

Lazar Ljubenović
Lazar Ljubenović

Reputation: 19764

Angular's HttpClient allows defining global interceptors.

You can define a simple interceptor which does nothing like this:

@Injectable()
export class NoopInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req);
  }
}

List it in the providers of an Angular module (you probably want AppModule), as the following.

{
  provide: HTTP_INTERCEPTORS,
  useClass: NoopInterceptor,
  multi: true,
}

All your requests will now pass through this interceptor.

For more information, read about HttpClient interceptors in Angular in the official guide. There you can find the exact use-case which you want: setting headers on every request.

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private auth: AuthService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Get the auth header from the service.
    const authHeader = this.auth.getAuthorizationHeader();
    // Clone the request to add the new header.
    const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
    // Pass on the cloned request instead of the original request.
    return next.handle(authReq);
  }
}

All code is copied from the docs.

Upvotes: 6

Related Questions