Search code examples
angulartypescripttokeninterceptorreferrer-policy

Angular interceptor request failed because of strict-origin-when-cross-origin


I'm trying to implement access token handling in my Angular application, using an interceptor.

In the Spring backend I set some routes to be public (eg. localhost:8080/api/public/hello) and some to be able to be accessed only with an access token (eg. localhost:8080/api/hello). I also disabled the CORS support by overriding the WebMvcConfigurer.

If a component is calling a public API, the interceptor works fine, the Authorization header is added, but obviously it is not needed to load the page, but it was set properly and it seems to be working just fine.

However, if I'm about to call a non-public API, the interceptor fails to be working: two requests will be called, the first contains the Authorization header but it is not working, the other one does not have the header, and is not reached. The details are shown on the pictures below.

My interceptor code is simply cloning the request parameter and setting the headers, and the API calling is a very simple row in a component. The related imports are added and the modules, providers should be correct (public API works so the interceptor itself should be okay).

Interceptor (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);
}

Component (home.component.ts): (.helloPublic and .hello are the method names)

ngOnInit(): void {
  this.helloApi.helloPublic().subscribe((response: HelloDto) => {
    this.hello = response;
  });
}

Solution

  • Found the problem, http.cors() was missing from the configure(HttpSecurity http) method of my custom WebSecurityConfigurerAdapter:

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