【问题标题】:How do I set the authorisation header to a bearer token generated for other API requests如何将授权标头设置为为其他 API 请求生成的不记名令牌
【发布时间】:2020-12-03 20:17:51
【问题描述】:

我创建了一个调用第三方端点的服务。 我已经使用他们的身份验证端点生成了一个承载令牌,我需要将其与其他 api 调用一起使用。

由于这是一个第 3 方 API,我正在调用我的目标网址,并且标头是在代理上构建的。

既然我已经生成了 access_token,我该如何将此字符串添加到授权标头中?

组件

 showOAuth() {
    this.zebraService.getOAuth()
      .subscribe((data: any) => {
      console.log('Zebra Response: ', data);
      console.log(data.body);
      this.OAuth = data.body;

      this.access_token = this.OAuth.access_token;
      console.log(this.access_token);
      });
  }

代理

"/zebraAccessApi": {
  "target": "https://api.com",
  "secure": true,
  "changeOrigin": true,
  "pathRewrite": {
    "^/zebraAccessApi": ""
  },
  "headers": {
    "client_id": "",
    "client_secret": ""
  }
},

"/zebraSetAppLed": {
  "target": "https://api.com/setAppLed",
  "secure": true,
  "changeOrigin": true,
  "pathRewrite": {
    "^/zebraSetAppLed": ""
  },
  "headers": {
    "Content-Type": "application/json",
    "Authorization": ""
  }
}

服务

zebraOAuthUrl = '/zebraAccessApi';
    zebraSetAppLedUrl = '/zebraSetAppLed';

    public getOAuth() {    
        let options = {
            observe: 'response' as 'body',
            response: 'json'
        };
        return this.http.get(this.zebraOAuthUrl, options);
    }

【问题讨论】:

标签: angular typescript proxy


【解决方案1】:

您可以编写一个拦截器来添加必要的标头:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  const token = <YOUR_TOKEN>;

  // if no token add some default stuff or just return the req
  const reqNoToken = request.clone({
    setHeaders: {
      'Content-Type': 'application/json', 
    }
  });
  if (!token) {
    return next.handle(reqNoToken);
  }
  // this is basically where the magic happens
  const req = request.clone({
    setHeaders: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json',
    }
  });
  return next.handle(req).pipe(
    tap((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        // do stuff with response if you want
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        console.log(err)
      }
    })
  );
}

拦截器会按照其名称进行操作,它会拦截您的请求,并在上述情况下添加必要的令牌和标头,如果没有设置令牌,则不会。

我认为您必须根据需要更改功能,但我想这应该没问题。

另外请在此处阅读有关角度拦截器的信息,因为我不想详细介绍该概念:https://angular.io/api/common/http/HttpInterceptor

【讨论】:

  • 谢谢@chriszichrisz,我会阅读它,看看我是否可以让它为我工作。
  • 如何将拦截器设置为仅由某些 API 调用而不是所有 API 调用使用?
  • afaik 这是不可能的,据我了解,仅对某些调用使用拦截器并不是它的设计方式。如果您只有一个调用,您可以直接在 .get(url: string, options?: { headers?: HttpHeaders } ... 上设置标头...或者您在拦截器中创建一个基于 request.url 执行的条件并返回所有其他人。我真的建议你阅读 angular 文档,因为如何在单个请求上更改标头实际上是 angular 101 并且它有很好的记录,不仅在官方文档中,而且在许多其他教程中。
猜你喜欢
  • 2013-09-03
  • 1970-01-01
  • 1970-01-01
  • 2019-01-01
  • 2013-07-07
  • 2013-10-30
  • 2021-08-02
  • 2020-11-24
  • 2020-10-18
相关资源
最近更新 更多