everyone. I\'m new to Angular 2 and Spring Framework. I\'m trying a simple get request with an authorization header (basic auth).
I\'m using Spring Boot (1.2.6.RELEA
Another option as in spring security guide:
in security config class which extends WebSecurityConfigurerAdapter configure cors()
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and().**this will use corsConfigurationSource by** default.
so lets define corsConfigurationSource
// other criteria
}
**so lets define corsConfigurationSource**
@Bean CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://myufrontend.com"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
}
This could be very late but this could solve some ones problem, after long hours i found the answer
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
public void configure( WebSecurity web ) throws Exception
{
web.ignoring().antMatchers( HttpMethod.OPTIONS, "/**" );
}
}
Refer https://stackoverflow.com/a/45830981/3724760
If there is anyone getting into the similar situation working around with Spring Boot, Spring Security and clients like angular 2/4, I've posted the findings here.
For those who are looking for a short answer, you have to configure two things:
With Spring Boot, the recommended way to enable global CORS is to declare within Spring MVC and combined with fine-grained @CrossOrigin
configuration as:
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
.allowedHeaders("*");
}
};
}
}
Then, while working with Spring Security, you have to enable CORS at Spring Security level as well to allow it to leverage the configuration defined at Spring MVC level as:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()...
}
}
Cheers!!!
avoid filtering and set status 200 when http method is OPTIONS
if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}