一尘不染

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

go

这是我的第一篇文章。

我刚刚开始学习Go和Angular,并且尝试将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代码中使用了大猩猩/多路复用器和大猩猩/处理程序

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 Dev Tools的标题

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

阅读 187

收藏
2020-07-02

共1个答案

一尘不染

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

AuthInterceptor是我在应用程序中使用的的完整示例:

验证拦截器

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

...

你可以阅读有关该方法进一步在这个岗位


关于 Go 方面,这很可能是您发送的
请求 标头与 CORS 允许的标头不匹配的情况。
您应该尝试的第一件事是允许所有这些:

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

并且,如果问题消失了,请尝试根据客户发送的内容仔细构造您的 CORS

2020-07-02