How to add Authorization Header to Angular http request?

烂漫一生 提交于 2019-11-25 15:18:12

Regarding the best way of handling Authentication headers in Angular > 4 it's best to use
Http Interceptors for adding them to each request, and afterwards using
Guards for protecting your routes.

Here's a full example of an AuthInterceptor that I'm using in my app:

auth.interceptor.ts

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

import { Observable } from 'rxjs/Observable';

import { AuthService } from './auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    req = req.clone({
      setHeaders: {
        'Content-Type' : 'application/json; charset=utf-8',
        'Accept'       : 'application/json',
        'Authorization': `Bearer ${AuthService.getToken()}`,
      },
    });

    return next.handle(req);
  }
}

You'll need to register your interceptor in the app.module as a provider:

app.module.ts

import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { AuthInterceptor } from '../auth/auth.interceptor';

...

imports: [
    HttpClientModule,
    ...
],
providers: [
    {
      provide : HTTP_INTERCEPTORS,
      useClass: AuthInterceptor,
      multi   : true,
    },
    ...
],

...

You can read about this method further in this post.


Regarding the Go's side of things, this is most likely a case of mismatch between
Request Headers you're sending and the headers CORS allow.
First thing you should try is allowing all of them:

headersOk := handlers.AllowedHeaders([]string{"*"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})

And if the problem goes away try carefully structuring your CORS one by one to what your client is sending.

In case you don't want to add interceptor, this worked for me:

var header = {
  headers: new HttpHeaders()
    .set('Authorization',  `Basic ${btoa(AuthService.getToken())}`)
}

this.http.get(url, header)

For Bearer,

set('Authorization',  `Bearer ${AuthService.getToken()}`)

Here is an example:

this.http
        .get(url, return new RequestOptions({
          headers: new Headers({
            Authorization: `Bearer ${authtoken}`
          }),
        }))
        .map(res => res.json());
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!