【发布时间】:2021-12-28 02:26:40
【问题描述】:
我正在尝试使用拦截器在我的 Angular 应用程序中实现访问令牌处理。
在 Spring 后端,我将一些路由设置为公开的(例如 localhost:8080/api/public/hello),而有些路由只能使用访问令牌访问(例如 localhost:8080/api/hello)。我还通过 overriding the WebMvcConfigurer 禁用了 CORS 支持。
如果一个组件正在调用 public API,拦截器工作正常,添加了 Authorization 标头,但显然不需要加载页面,但设置正确,似乎工作正常。
但是,如果我要调用 non-public API,拦截器将无法工作:将调用两个请求,第一个包含 Authorization 标头但它不工作,另一个没有标题,也没有到达。详情如下图所示。
- Working call seen on Network on public API
- First failing hello call when calling non-public API
- Second unreachable hello call when calling non-public API
我的拦截器代码只是简单的克隆请求参数和设置标头,API 调用是一个组件中非常简单的一行。添加了相关的导入,并且模块、提供程序应该是正确的(公共 API 工作,所以拦截器本身应该没问题)。
拦截器(token-interceptor.service.ts):
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<unknown>> {
const authReq = req.clone({
setHeaders: {
Authorization: this.getAccessToken()
}
});
return next.handle(authReq);
}
组件(home.component.ts): (.helloPublic 和 .hello 是方法名)
ngOnInit(): void {
this.helloApi.helloPublic().subscribe((response: HelloDto) => {
this.hello = response;
});
}
【问题讨论】:
标签: angular typescript token interceptor referrer-policy