How to enable CORS at Spring Security level in Spr

2019-02-20 13:54发布

I am working with a spring boot application which uses Spring Security. I have tried @CrossOrigin to enable cors but it didn't work.

If you want to find my error refer this

Spring Blogs says that when we are working with spring security, we must enable cors at spring security level.

And my project is below.

Can anyone explain where should I put those configuration and how to find the spring security level.

2条回答
smile是对你的礼貌
2楼-- · 2019-02-20 14:01

this is a way to make Spring Security 4.1 support CROS with Spring BOOT 1.5

  @Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
           .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
    }
}

with

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.csrf().disable();
        http.cors();
    }
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(ImmutableList.of("*"));
        configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
查看更多
闹够了就滚
3楼-- · 2019-02-20 14:24

If you prefer using CORS global configuration, you can declare a CorsConfigurationSource bean as following:

@EnableWebSecurity
public class WebSecurityConfig extends 
WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws 
Exception {
    http.cors().and()...
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    UrlBasedCorsConfigurationSource source = new 
UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
    return source;
   }
   }

For further refernces about spring boot project examples 1)https://hellokoding.com/registration-and-login-example-with-spring-security-spring-boot-spring-data-jpa-hsql-jsp/ Or 2)http://www.mkyong.com/spring-boot/spring-boot-spring-security-thymeleaf-example/

查看更多
登录 后发表回答