代码之家  ›  专栏  ›  技术社区  ›  Mohit Kanwar

弹簧靴:CORS问题

  •  2
  • Mohit Kanwar  · 技术社区  · 6 年前

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

    @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(包括permitAll登录)。

    在浏览器上我得到(它的工作与邮递员,因为CORS检查没有做那里)

    加载失败 http://localhost:8080/myurl :对飞行前的响应 请求未通过访问控制检查:否 请求的 资源。起源' http://localhost:4200 因此不允许 进入。响应的HTTP状态代码为403。

    3 回复  |  直到 6 年前
        1
  •  7
  •   priteshbaviskar    6 年前

    虽然Spring安全性提供了一种在http配置器中配置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() {
    }
    
    }
    

    以最高优先级排序筛选器,确保MyCORSFilter实现 javax.servlet.Filter 是链条上的第一个。希望这有帮助

        2
  •  2
  •   Paulo van Goethe    6 年前

    好吧,所以我意识到它已经被弃用了。如果你看一下baeldung,自从他们更新了webmvcconfiguer之后,它就有了新的方法:

    @Configuration
    @EnableWebMvc
    public class WebConfig implements WebMvcConfigurer {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedMethods("*").allowedOrigins(frontDomain);
        }
    }
    
        3
  •  1
  •   nmyk    6 年前

    从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));
    }