Angular frontend cannot communicate with Spring Boot backend after security setup

I’m facing issues when my Angular app tries to reach my Spring Boot REST API. Everything worked fine before I added Spring Security configuration. Now I get authentication errors and the preflight OPTIONS requests don’t seem to work properly.

Here’s my security config:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {    
        httpSecurity.csrf().disable();
        httpSecurity.authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .httpBasic();
    }
}

On the Angular side I have this service method:

callUserDataService(username) {
  const authHeader = this.buildAuthHeader();
  
  const httpHeaders = new HttpHeaders({
      Authorization: authHeader
    });
  return this.http.get<UserData>(`http://localhost:8080/api/user-data/${username}`,
    {headers: httpHeaders});
}

buildAuthHeader() {
  const user = 'admin';
  const pass = 'secret';
  const authString = 'Basic ' + window.btoa(user + ':' + pass);
  return authString;
}

I already added @CrossOrigin annotation to my controller but still getting CORS errors. The browser shows 401 Unauthorized instead of making the preflight request first. What am I missing in my setup?

check if ur sending an auth header - it can turn requests into “complex” ones that need preflight. try removing the auth header and see if cors works. if it does, then that’s ur issue. u might have to allow authorization in your cors config.

This looks like a CORS config issue, not auth. Your @CrossOrigin on the controller won’t help here - Spring Security handles CORS separately and can override it. Add .cors() to your HttpSecurity chain and create a CorsConfigurationSource bean. That way Spring Security deals with preflight OPTIONS requests before hitting your auth logic. I’ve seen this before where browsers skip preflight for simple requests but still trigger authentication. The 401 you’re getting means the request hits your auth filter before CORS finishes processing. Fixed it for me when I moved the CORS config to the security level.

hmm, got any http interceptors running that could be messing with cors preflight timing? does this happen on all your endpoints or just some? try a simple get to a public endpoint first - that’ll tell you if it’s cors or auth causing the problem.