10

I'm new to angular and trying to setup HTTP Authorization Headers. As of now I'm able to set authorization headers for all API's if token is valid. What I want is to set header for some API's only even if token is available.

app.module.ts

@NgModule({
  declarations: [AppComponent],
  imports: [
    HttpClientModule
  ],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
  ]
})

jwt.interceptor.ts

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

    import { AuthenticationService } from '@/_services';
    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs';

    @Injectable()
    export class JwtInterceptor implements HttpInterceptor {
        constructor(private authenticationService: AuthenticationService) {}

        intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            // add authorization header with jwt token if available
            const currentUser = this.authenticationService.currentUserValue;
            if (currentUser && currentUser.token) {
                request = request.clone({
                    setHeaders: {
                        Authorization: `Bearer ${currentUser.token}`
                    }
                });
            }

            return next.handle(request);
        }
    }

home-http.service.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class HomeHttpService {
    constructor(private http: HttpClient) { }

    getAll(url: string, paramsVal?: any): Observable<any[]> {
        const options = {params: paramsVal};
        return this.http.get<any[]>(url, options);
    }

    public getByID(url: string, id: number | string): Observable<any> {
        return this.http.get<any>(`${url}/${id}`);
    }

    public delete(url: string): Observable<any> {
        return this.http.delete<any>(url).pipe(
            map(response => {
                return response;
            })
        );
    }

    public post(data = [], url: string): Observable<any> {
        return this.http.post<any>(url, data);
    }

    public getExternal(url: string): Observable<any> {
        return this.http.get<any>(url);
    }

    public put(data: any, url: string): Observable<any> {
        return this.http.put<any>(url, data);
    }
}

home.service.ts

import { Injectable } from '@angular/core';

import { HomeHttpService } from '../home-http.service';
import { Observable } from 'rxjs';

@Injectable()
export class HomePageService {
  constructor(private apiservice: HomeHttpService) {}
  private basePath = `${url}`;

getAlldata(data): Observable<any> {
    return this.apiservice.getAll(this.basePath, data);
  }

How can I setup my code so that for some API's I can remove the authorization header for some APIs

1
  • Please tell me what I can do to improve my question before downvoting Commented Oct 14, 2019 at 12:44

3 Answers 3

9

In those service files use this way

import {HttpBackend, HttpClient} from "@angular/common/http";

constructor(private http: HttpClient, handler: HttpBackend ) {
    this.http = new HttpClient(handler);
}
Sign up to request clarification or add additional context in comments.

2 Comments

the easiest solution is the best solution
No need to inject httpClient, you can remove it from constructor and include it as a field: http: HttpClient;
7

You can use the request.url property to filter what you need. One of the easiest ways:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // add authorization header with jwt token if available
    const currentUser = this.authenticationService.currentUserValue;
    if (request.url.indexOf('some APIs path') === 0 && currentUser && currentUser.token) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${currentUser.token}`
        }
      });
    }

    return next.handle(request);
  }

3 Comments

can you ellaborate or give an example
one of the easiest ways: intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // add authorization header with jwt token if available const currentUser = this.authenticationService.currentUserValue; if (request.url.indexOf('some APIs path') === 0 && currentUser && currentUser.token) { request = request.clone({ setHeaders: { Authorization: `Bearer ${currentUser.token}` } }); } return next.handle(request); }
This does not look like a standard solution.
1

To be more precise, you can take a look at the example below

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

import { AuthenticationService } from '@/_services';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with jwt token if available
        const currentUser = this.authenticationService.currentUserValue;
        if (this.isHeaderNeeded() &&currentUser && currentUser.token) {
            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${currentUser.token}`
                }
            });
        }

        return next.handle(request);
    }
}

isHeaderNeeded(url: string) {
    if (url === "other.api.com") { // this condition is up to you, it could be an exact match or how ever you like
        return false;
    } else {
        return true;
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.