Spring Boot,Cors和Spring Security

时间:2019-02-22 19:48:22

标签: java spring-boot spring-security cors

我正在使用Spring Boot 2.0.8.RELEASE版本和spring-boot-start-security模块。 我正在尝试通过基本身份验证来保护我的摇摇欲坠的端点,到目前为止一切都很好。 但是,我代码中来自javascript的请求已开始失败,并显示以下错误

Access to XMLHttpRequest at 'http://my-service.com.com/search/api/getQuery' from origin 'http://myui.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

我定义了以下配置类

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //See https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-cors-global-java for configuring cors
        registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").allowedHeaders("*");
    }

}

我的API类上带有@CrossOrigin批注。 而且我有以下课程来配置我的安全性

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()
             .and()
             .csrf().disable()
                .authorizeRequests()
                    .antMatchers("/v2").authenticated()
                    .antMatchers("/swagger-resources").authenticated()
                    .antMatchers("/swagger-ui.html").authenticated()                    
                    .and()
                    .httpBasic()
                    .and()
                    .authorizeRequests()    
                        .antMatchers("/**").permitAll()
                        .and();        

    }

    }

我尝试在安全性类中创建CorsConfiguration并删除@CrossOrigin批注,但这也不起作用。 为了使cors在Spring Boot 2.0.8.RELEASE上正常工作,我需要做什么吗?

谢谢 达米安

1 个答案:

答案 0 :(得分:0)

以我的经验,Spring Annotations从未成功解决CORS问题。 我首选的解决方案是通过虚拟主机路由两个服务器(在我的情况下为Node和Tomcat)。

在我的Apache httpd-vhosts配置文件中,我具有以下设置。

    ProxyRequests Off
    ProxyPreserveHost Off
    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    <Location /FrontEndServer>
        ProxyPass        http://localhost:8080/FrontEndServer connectiontimeout=333 timeout=999
        ProxyPassReverse http://localhost:8080/FrontEndServer
    </Location>

    <Location />
        ProxyPass        http://localhost:3000/ connectiontimeout=333 timeout=999
        ProxyPassReverse http://localhost:3000/
    </Location>

在此设置中,我的两个服务器在不同的端口上运行,但是Apache重新路由它们,以便它们可以共享我的本地主机,并可以通过“ /”或“ / FrontEndServer”进行区分。

显然,这是特定于Apache的,可能不是您使用的设置。但是,您应该能够使用这些原则为您的特定情况找到解决方案。希望这可以帮助。