春季启动:CORS问题

时间:2018-08-07 06:08:16

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

我正在使用Spring Boot版本2.0.2Release。 下面是我的安全配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        prePostEnabled = true,
        securedEnabled = true,
        jsr250Enabled = true)
@ComponentScan("com.mk")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationProvider myAuthenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.cors().configurationSource(corsConfigurationSource())
                .and()
                .csrf().disable()
                .anonymous().and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET,"/index.html").permitAll()
                .antMatchers(HttpMethod.POST,"/login").permitAll()
                .antMatchers(HttpMethod.GET,"*").authenticated()
                .and().httpBasic();
    }
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

由于CORS问题,我无法调用任何API(包括登录为allowAll)。

在浏览器中,我得到了它(它与Postman一起使用,因为在那里没有进行CORS检查)

  

无法加载http://localhost:8080/myurl:对预检的响应   请求未通过访问控制检查:否   请求中存在“ Access-Control-Allow-Origin”标头   资源。因此,不允许原点“ http://localhost:4200”   访问。响应的HTTP状态码为403。

4 个答案:

答案 0 :(得分:6)

无需添加任何其他FiltersWebMvcConfigurer。主要问题是'Access-Control-Allow-Origin'没有出现在标头中,因为corsConfigurationSource没有添加必要的配置来获取相关的CORS响应标头。因此,当我们配置CorsConfigurationSource

时,必须添加以下缺少的配置
configuration.addAllowedOrigin("*");
configuration.addAllowedHeader("*");
configuration.addAllowedMethod("*");

我们必须按如下所示配置cors CorsConfigurationSource

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

 @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowCredentials(true);
        //the below three lines will add the relevant CORS response headers
        configuration.addAllowedOrigin("*");
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

答案 1 :(得分:4)

尽管Spring安全性提供了一种在http configurer中配置CORS的方法,但是有一种更加干净的方法可以将CORS过滤器添加到应用程序中-

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyCORSFilter implements Filter {


@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

    chain.doFilter(req, res);
}

@Override
public void init(FilterConfig filterConfig) {
}

@Override
public void destroy() {
}

}

对过滤器进行最高优先级排序可确保javax.servlet.Filter的MyCORSFilter实现是该链中的第一个实现。希望这会有所帮助

答案 2 :(得分:2)

好,所以我意识到它已被弃用。自从他们更新了webmvcconfigurer以来,如果您查看baeldung,它有新的方法:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("*").allowedOrigins(frontDomain);
    }
}

答案 3 :(得分:0)

从Spring查阅本指南:

https://spring.io/guides/gs/rest-service-cors/

在Spring Boot中添加CORS支持的方法很少。

使用全局配置:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
        }
    };
}

并使用@CrossOrigin批注:

@CrossOrigin(origins = "http://localhost:9000")
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
    System.out.println("==== in greeting ====");
    return new Greeting(counter.incrementAndGet(), String.format(template, name));
}