如何向Angular http请求添加授权标头?

时间:2017-11-20 20:57:27

标签: angular go gorilla

这是我的第一篇文章。

我刚刚开始学习Go和Angular,我正在尝试将角度应用程序连接到go api。我已经写过这两篇文章而且很难找出问题的根源。我认为这是一个CORS问题,但如果我不在Angular http请求中包含代码标题行,它可以正常工作。此时我只是想添加标题。授权码尚未实施。

两个应用程序都在本地运行,端口5000上的Go应用程序和4200上的Angular

不起作用的Angular http请求:

this.http.get<ProjectedBalance>(requestUrl, {headers: new HttpHeaders().set('Authorization', 'my-auth-token')})
    .subscribe(data => {
     this.projBalance = data.projBalance;
   }

有效的Angular http请求:

this.http.get<ProjectedBalance>(requestUrl)
    .subscribe(data => {
     this.projBalance = data.projBalance;
   }

我收到了这个错误:

  

对预检请求的响应未通过访问控制检查:否   请求中存在“Access-Control-Allow-Origin”标头   资源。因此不允许来源“http://localhost:4200”   访问。响应具有HTTP状态代码403

我在go代码中使用gorilla / mux和gorilla / handlers

router := mux.NewRouter()
router.HandleFunc("/home/{endDate}", GetProjBalance).Methods("GET", "OPTIONS")
headersOk := handlers.AllowedHeaders([]string{"X-Requested-With, Content-Type, Authorization"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
//start server on port
log.Fatal(http.ListenAndServe(":5000", handlers.CORS(originsOk, headersOk, methodsOk)(router)))

Chrome开发者工具中的标题

Request URL:http://localhost:5000/home/2020-12-21
Request Method:OPTIONS
Status Code:403 Forbidden
Remote Address:[::1]:5000
Referrer Policy:no-referrer-when-downgrade

Response Headers
view source
Content-Length:0
Content-Type:text/plain; charset=utf-8
Date:Mon, 20 Nov 2017 21:39:43 GMT

Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9,uz;q=0.8
Access-Control-Request-Headers:authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:5000
Origin:http://localhost:4200

5 个答案:

答案 0 :(得分:25)

关于在 Angular&gt;中处理身份验证标头的最佳方法4 最好使用
Http Interceptors将其添加到每个请求中,然后使用
Guards用于保护您的路线。

以下是我在我的应用中使用AuthInterceptor的完整示例:

  

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);
  }
}

您需要在app.module中注册您的拦截器作为提供商:

  

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,
    },
    ...
],

...

您可以在此post进一步了解此方法。

关于 Go 的一面,这很可能是两者之间不匹配的情况 请求标题您正在发送,标题 CORS 允许。
你应该尝试的第一件事是允许所有这些:

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

如果问题消失,请尝试将 CORS 逐个构建到客户端发送的内容中。

答案 1 :(得分:1)

角度6 ==>具有授权标头的HTTP获取请求示例

public IsClientCreditCardExits(companyId: string, token: any) {
    let header = new Headers({ 'Authorization': `Bearer ${token}` });
    const options = new RequestOptions({
       headers: header,
    });
    return this._http.get(this.ApiURL + "api/Subscriptions/IsClientCreditCardExits/" + companyId + "/", options);    
}

答案 2 :(得分:0)

以下是一个例子:

this.http
        .get(url, return new RequestOptions({
          headers: new Headers({
            Authorization: `Bearer ${authtoken}`
          }),
        }))
        .map(res => res.json());

答案 3 :(得分:0)

如果您不想添加拦截器,这对我有用:

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

this.http.get(url, header)

对于承载者,

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

答案 4 :(得分:0)

以下示例非常适合您仅在访问需要授权的资源时才添加一些标头的情况,请参见下面的代码。请注意,您需要在 authentication.service.ts 中创建getToken方法。

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);
    }
  }
}

app.module.ts 中注册拦截器,如下所示:

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 {}