【问题标题】:Angular interceptor request failed because of strict-origin-when-cross-originAngular 拦截器请求因 strict-origin-when-cross-origin 而失败
【发布时间】: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 标头但它不工作,另一个没有标题,也没有到达。详情如下图所示。

我的拦截器代码只是简单的克隆请求参数和设置标头,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


    【解决方案1】:

    发现问题,我的自定义 WebSecurityConfigurerAdapter 的 configure(HttpSecurity http) 方法中缺少 http.cors()

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors();
            // (...)
        }
    
        // (...)
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-06
      • 2021-05-16
      • 2021-02-19
      • 1970-01-01
      • 2022-07-01
      • 2021-08-08
      • 2018-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多