如何在Spring启动时在Spring Security级别启用CORS

时间:2018-02-22 11:38:20

标签: java spring spring-boot spring-security cors

  

我正在使用Spring的Spring启动应用程序   安全。我已经尝试过@CrossOrigin来启用角色,但它没有用。

如果您想查找我的错误,请参阅this

Spring Blogs说当我们使用 spring security 时,我们必须在春季安全级别启用cors

我的项目如下。

任何人都可以解释我应该在哪里放置这些配置以及如何找到弹簧安全级别。

2 个答案:

答案 0 :(得分:6)

这是一种通过Spring BOOT 1.5使Spring Security 4.1支持CROS的方法

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

@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;
    }
}

答案 1 :(得分:3)

如果您更喜欢使用CORS全局配置,可以如下声明CorsConfigurationSource bean:

@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;
   }
   }

有关spring boot项目示例的进一步参考 1)https://hellokoding.com/registration-and-login-example-with-spring-security-spring-boot-spring-data-jpa-hsql-jsp/ 要么 2)http://www.mkyong.com/spring-boot/spring-boot-spring-security-thymeleaf-example/