angular - Angular 9 http拦截器获取Aws accesstoken
问题描述
我正在按照这个在Angular HTTP 拦截器中添加 AWS 访问令牌,但是代码进入无限循环,我收到net::ERR_INSUFFICIENT_RESOURCES
错误。
显示单个字符的令牌值的 console.log。
先感谢您
这是代码
服务.ts
getAccessToken(): Observable<string> {
return from(Auth.currentSession()).pipe(
switchMap(session => from(session.getAccessToken().getJwtToken()))
);
}
拦截器.ts
/* eslint-disable no-param-reassign */
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { UserService } from 'app/user.service';
import { switchMap } from 'rxjs/operators';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(public userService: UserService) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return this.userService.getAccessToken().pipe(
switchMap(jwtToken => {
console.log(jwtToken);
// clone the request to add the new header.
req = req.clone({
headers: req.headers.set('Authorization', `Bearer ${jwtToken}`),
});
if (!req.headers.has('Content-Type')) {
req = req.clone({
headers: req.headers.set('Content-Type', 'application/json'),
});
}
return next.handle(req);
})
);
}
}
解决方案
在拦截器中使用 http 请求不是一个好习惯。相反,您可以在应用程序打开时拉一次“jwtToken”并将其导入 localStarege。
在 app.module.ts
import {UserService} from './UserService';
export function appInitializerFn(userService: UserService) {
return (): Promise<boolean> => userService.getJwtToken()
}
...
@NgModule({
providers : [UserService, {
provide: APP_INITIALIZER,
useFactory: appInitializerFn,
multi: true,
deps: [UserService]
},] )
在 UserService.ts
@Injectable()
export class UserService {
constructor(private http: HttpClient) {
}
getJwtToken(): Promise<any> {
return this.http
.get('get/toke/url'))
.toPromise()
.then((data: any) => {
localStorage.setItem("jwtToken", data);
}).catch((err: Error) => {
}).finally(() => {
console.info(' token init ');
return Promise.resolve(true)
})
}
}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const jwtToken: string = localStorage.getItem('jwtToken');
req = req.clone({
headers: req.headers.set('Authorization', `Bearer ${jwtToken}`),
});
if (!req.headers.has('Content-Type')) {
req = req.clone({
headers: req.headers.set('Content-Type', 'application/json'),
});
}
return next.handle(req);
);