如何将授权标头添加到Angular http请求? [英] How to add Authorization Header to Angular http request?

查看:92
本文介绍了如何将授权标头添加到Angular http请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一篇文章.

我刚刚开始学习Go和Angular,并且尝试将angular应用程序连接到go api.我已经写了这两本书,并且一直坚持找出问题的根源.我以为这是一个CORS问题,但是如果我在Angular http请求中不包含代码的标头行,它就可以正常工作.在这一点上,我只是想添加标题.授权代码尚未实现.

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 identifying the root of the problem. I thought it was a CORS problem, but it works fine if I don't include the headers line of code in my Angular http request. At this point I'm just trying to add the header. The authorization code isn't implemented yet.

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

Both apps are running locally with the Go app on port 5000 and Angular on 4200

无法使用的角度http请求:

Angular http request that doesn't work:

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

有效的有角http请求:

Angular http request that works:

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

我收到此错误:

对预检请求的响应未通过访问控制检查:否 请求中存在"Access-Control-Allow-Origin"标头 资源.因此,不允许使用来源" http://localhost:4200 " 使用权.响应的HTTP状态码为403

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403

我在go代码中使用了大猩猩/多路复用器和大猩猩/处理程序

I'm using the gorilla/mux and gorilla/handlers in my go code

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开发工具中的标题

Headers from 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

推荐答案

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

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.

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

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

auth.interceptor.ts

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中将拦截器注册为提供程序:

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

app.module.ts

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 这些标题.
您应该尝试的第一件事就是允许所有人:

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

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

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

这篇关于如何将授权标头添加到Angular http请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆