I am using JWT in my Spring Boot app. When I try to login from the Angular 6 client, I get the CORS error
Access to XMLHttpRequest at \'http://localhost:8082
1) Create a bean returning CorsFilter
I did it in SecurityConfig
class which extends WebSecurityConfigurerAdapter
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final JwtTokenProvider jwtTokenProvider;
@Autowired
public SecurityConfig(JwtTokenProvider jwtTokenProvider) {
this.jwtTokenProvider = jwtTokenProvider;
}
@Override
public void configure(HttpSecurity http) throws Exception {
//....
http.cors();
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("GET");
config.addAllowedMethod("POST");
config.addAllowedMethod("PUT");
config.addAllowedMethod("DELETE");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
2) Provide this CorsFilter
to the class extending SecurityConfigurerAdapter
public class JwtConfigurer extends SecurityConfigurerAdapter {
private final JwtTokenProvider jwtTokenProvider;
public JwtConfigurer(JwtTokenProvider jwtTokenProvider) {
this.jwtTokenProvider = jwtTokenProvider;
}
@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
JwtTokenFilter jwtTokenFilter = new JwtTokenFilter(jwtTokenProvider);
httpSecurity.addFilterBefore(
new SecurityConfig(jwtTokenProvider).corsFilter(),
UsernamePasswordAuthenticationFilter.class);
httpSecurity.addFilterBefore(
jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);
}
}
3) Add in method configure(HttpSecurity http) { /* ... */ http.cors(); }
in SecurityConfig
class
Shown in the first code snippet above.