我如何在 AuthInterceptor 类中获取/使用 accessToken 并将其添加到每个 API (.NetCore) 调用中。
我已经实现了
getAccessToken() {
return Auth.currentSession().then(res => {
return res.getAccessToken().getJwtToken();
});
}
在authService 中,但我似乎无法在intercept(req: HttpRequest, next: HttpHandler){} 方法中使用它。我可以实现的任何方式或流程更改。
最佳答案
首先,将您的 promise 转换为 Observable
进入您的 AuthService.ts
:
import { from } from 'rxjs';
import { switchMap } from 'rxjs/operators';
...
getAccessToken(): Observable<string> {
return from(Auth.currentSession()).pipe(
switchMap(session => from(session.getAccessToken().getJwtToken())
)
};
然后您就可以轻松地将它用于您的
AuthHttpInterceptor
:@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
constructor(
private authService: AuthService
) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.authService.getAccessToken().pipe(
switchMap(jwtToken => {
// clone the request to add the new header.
const authReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${jwtToken}`)
});
return next.handle(authReq);
})
);
}
}
关于angular - 我如何在 Angular 8 的 AuthInterceptor 类中获取/使用 accessToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60611949/