简体   繁体   English

在 Spring Boot 中全局启用 CORS

[英]Enabling CORS globally in Spring Boot

I tried to enable CORS globally like this:我尝试像这样在全球范围内启用 CORS:

@Configuration
@ComponentScan("com.example")
@EnableWebMvc
public class OriginFilter extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE");
    }
}

I also tried this approach:我也尝试过这种方法:

@Configuration
public class OriginFilter implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD")
                .allowCredentials(true);
    }
}

But none of these worked for me.但这些都不适合我。

An annotation @CrossOrigin for an individual class works, but I wanted to enable CORS it globally.单个类的注释@CrossOrigin有效,但我想全局启用 CORS。

You could indeed define your own Filter as you mentioned in your answer.正如您在回答中提到的那样,您确实可以定义自己的Filter Spring already has such a CorsFilter already though, so you don't have to create one yourself.不过,Spring 已经有了这样的CorsFilter ,因此您不必自己创建一个。 Just register it as a bean and it should work:只需将其注册为 bean,它应该可以工作:

@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    // Don't do this in production, use a proper list  of allowed origins
    config.setAllowedOrigins(Collections.singletonList("*"));
    config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

I solved this problem by adding filterClass我通过添加 filterClass 解决了这个问题

@Component
public class CORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept");
        response.setHeader("Access-Control-Expose-Headers", "Location");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

The working global CORS configuration using WebMvcConfigurer for me without using filter.为我使用WebMvcConfigurer而不使用过滤器的工作全局 CORS 配置。

@Configuration
public class GlobalCorsConfiguration {

    public GlobalCorsConfiguration() {
        super();
    }

    /**
     * Bean to define global CORS.
     * 
     * @return
     */
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
            }
        };
    }
}

Thanks.谢谢。

You can also do the following to enable CORS globally in Spring Boot application.您还可以执行以下操作以在 Spring Boot 应用程序中全局启用 CORS。 However please note that WebMvcConfigurerAdapter is deprecated.但是请注意,不推荐使用 WebMvcConfigurerAdapter。

@SuppressWarnings("deprecation")
@SpringBootApplication(exclude = org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class)
public class SpringbootMongodbDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMongodbDemoApplication.class, args);
    }
    @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**").allowedOrigins("*");
                }
            };
        }

Also in the Controller add the following-同样在控制器中添加以下内容 -

@PostMapping("/addfeedback")
@CrossOrigin(origins = "*")
public FeedbackForResolution addFeedback(@RequestBody FeedbackForResolution feedback) {
.
.
.
}

here is the solution for your approach.这是您的方法的解决方案。 this is working fine as expected.这按预期工作正常。 it may be too late.可能为时已晚。 but it will be useful for someone.但这对某人有用。

there are two ways to enable globally.有两种方法可以全局启用。

1.One is through creating bean. 1.一种是通过创建bean。 2.other one is thorugh annotaion 2.另一个是完整的注释

1st Method:第一种方法:

@Configuration
public class CorsConfiguration {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedOrigins("*")
                .allowedHeaders("*");
            }
        };
    }
}

2nd method:方法二:

by adding @CrossOrigin annotation on the top of the controller class.通过在控制器类的顶部添加@CrossOrigin注释。

but First Two methods is not working for PUT Request for me.但前两种方法不适用于我的 PUT 请求。 For Put Method, you can use the following approach.对于 Put Method,您可以使用以下方法。

The following approach will work for all the type of requests.以下方法适用于所有类型的请求。

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("DELETE");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

}

I have had issues with this problem as well and have attempted to use some of solutions listed on this page, I had little success.我也遇到过这个问题,并尝试使用此页面上列出的一些解决方案,但收效甚微。 I am using spring boot version 2.1.2.RELEASE.我正在使用 Spring Boot 版本 2.1.2.RELEASE。

This solved it for me,这为我解决了它,

import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
blah
blah


    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true); 
        config.addAllowedOrigin("http://localhost:4200");
        config.addAllowedHeader("*");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

Where blah blah is the rest of my code. blah blah 是我的其余代码。

I have no idea why this method worked for me and the others did not, it allowed my typescript application making connections from localhost:4200 to connect to my spring boot application running on localhost:8080我不知道为什么这种方法对我有用而其他方法没有,它允许我的打字稿应用程序从 localhost:4200 连接到我在 localhost:8080 上运行的 Spring Boot 应用程序

Hi I have gone through this issue(Global Configuration wasn't working) recently!嗨,我最近遇到了这个问题(全局配置不起作用)! and I found something useful.我发现了一些有用的东西。

We should NOT add backslash at the end like this http://localhost:4200/ Basically it should be http://localhost:4200 (not backslash at end)我们应该像这样在末尾添加反斜杠http://localhost:4200/基本上它应该是http://localhost:4200 (最后不是反斜杠)

I fixed this issue by adding the following config class :我通过添加以下配置类解决了这个问题:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

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

This method enables CORS requests from any origin to any endpoint in the application.此方法允许从任何来源到应用程序中的任何端点的 CORS 请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM