spring boot 启用全局 CORS 支持问题:只有 GET 有效,POST、PUT 和 Delete 无效

新手上路,请多包涵

更新:现在回顾一年多后,我给出了一个更新,希望能对其他人有所帮助。

Spring IO 建议对普通用户可以由浏览器处理的任何请求使用 CSRF 保护。如果您只是创建一个供非浏览器客户端使用的服务,您可能希望禁用 CSRF 保护。由于我的应用程序是一个 API,将由浏览器处理,因此禁用 CSRF 不是一种方法。

默认情况下,Spring Boot 启用了 CSRF,您需要添加以下代码来添加 CSRF 存储库和过滤器以将 CSRF 令牌添加到您的 http 请求。 (解决方案来自此处 Invalid CSRF Token in POST request

 @Override
protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/assets/**", "/templates/**", "/custom-fonts/**", "/api/profile/**", "/h2/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .logoutSuccessUrl("/login?logout")
                .permitAll()
                .and()
            .csrf().csrfTokenRepository(csrfTokenRepository())
                .and()
            .addFilterAfter(csrfHeaderFilter(), SessionManagementFilter.class); // Register csrf filter.
               }

过滤器和 CsrfToken 存储库部分:

 private Filter csrfHeaderFilter() {
    return new OncePerRequestFilter() {

        @Override
        protected void doFilterInternal(HttpServletRequest request,
                                        HttpServletResponse response,
                                        FilterChain filterChain) throws ServletException, IOException {

            CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
            if (csrf != null) {
                Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                String token = csrf.getToken();
                if (cookie == null || token != null
                        && !token.equals(cookie.getValue())) {

                    // Token is being added to the XSRF-TOKEN cookie.
                    cookie = new Cookie("XSRF-TOKEN", token);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
            filterChain.doFilter(request, response);
        }
    };
}

private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }


我在 2016 年 2 月提出的原始问题

我致力于使用 Spring 4 为 Spring-boot RESTful API 启用全局 CORS 支持。

我正在关注官方 Spring Boot Doc( https://spring.io/guides/gs/rest-service-cors/ )并将其添加到我的应用程序中:

 public class SomeApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(SomeApiApplication.class, args);
    }

    //Enable Global CORS support for the application
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("http://localhost:8080")
                        .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD")
                        .allowedHeaders("header1", "header2") //What is this for?
                        .allowCredentials(true);
            }
        };
    }
}

我不明白为什么只有 GET 有效,对于其余的 http 调用,我收到一条错误消息,指出“无效的 CORS 请求”。我是否遗漏了设置中的任何内容?如果我的设置不正确,GET 应该不会起作用。我很困惑。

原文由 Half Ass Dev 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 889
1 个回答

我有一个类似的问题,只有 HEAD GET 和 POST 对我有用。我发现 addCorsMappings 的默认值为 allowedMethods

此代码对我有用:

 import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedMethods("*")
                        .allowedOrigins("http://localhost:4200");
            }
        };
    }
}

原文由 Charles 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题