我创建了一个调用第三方端点的服务。 我已经使用他们的身份验证端点生成了一个不记名 token ,我需要将其与其他 api 调用一起使用。
由于这是一个第 3 方 API,我正在调用我的目标 URL,并且 header 是在代理上构建的。
现在我已经生成了 access_token,如何将此字符串添加到授权 header 中?
组件
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);
}
最佳答案
您可以编写一个拦截器来添加必要的 header :
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)
}
})
);
}
拦截器顾名思义,它会拦截您的请求,并在上述情况下添加必要的 token 和 header ,如果未设置 token ,则不会添加。
我认为您必须根据需要更改功能,但我想这应该没问题。
另请在此处阅读有关 Angular 拦截器的信息,因为我不想详细介绍该概念:https://angular.io/api/common/http/HttpInterceptor
关于angular - 如何将授权 header 设置为为其他 API 请求生成的不记名 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65125622/