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?