How to add Authorization Header to Angular http request?

后端 未结 5 598
悲&欢浪女
悲&欢浪女 2020-12-08 05:03

This is my first post.

I\'ve just started learning Go and Angular and I\'m attempting to connect the angular app to a go api. I\'ve written both and am stuck identi

5条回答
  •  孤街浪徒
    2020-12-08 05:42

    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,
        next: HttpHandler
      ): Observable> {
        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 {}
    

提交回复
热议问题