Java 在 Spring Boot 中全局启用 CORS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51720552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:13:39  来源:igfitidea点击:

Enabling CORS globally in Spring Boot

javaspring-bootcors

提问by Moler

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 @CrossOriginfor an individual class works, but I wanted to enable CORS it globally.

@CrossOrigin单个类的注释有效,但我想全局启用 CORS。

采纳答案by g00glen00b

You could indeed define your own Filteras you mentioned in your answer. Spring already has such a CorsFilteralready though, so you don't have to create one yourself. Just register it as a bean and it should work:

您确实可以Filter像您在回答中提到的那样定义自己的。Spring 已经有了这样的一个CorsFilter,所以你不必自己创建一个。只需将其注册为 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);
}

回答by Moler

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() {

    }
}

回答by Sushan Baskota

The working global CORS configuration using WebMvcConfigurerfor 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.

谢谢。

回答by Hirak JD

You can also do the following to enable CORS globally in Spring Boot application. However please note that WebMvcConfigurerAdapter is deprecated.

您还可以执行以下操作以在 Spring Boot 应用程序中全局启用 CORS。但是请注意 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) {
.
.
.
}

回答by Dave

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 m y typescript application making connections from localhost:4200 to connect to my spring boot application running on localhost:8080

我不知道为什么这个方法对我有用而其他方法没有,它允许我的打字稿应用程序从 localhost:4200 连接到我在 localhost:8080 上运行的 spring boot 应用程序

回答by karthick S

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. 2.other one is thorugh annotaion

1.一是通过创建bean。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 @CrossOriginannotation on the top of the controller class.

通过在控制器类的顶部添加@CrossOrigin注释。

but First Two methods is not working for PUT Request for me. For Put Method, you can use the following approach.

但是前两种方法对我来说不适用于 PUT 请求。对于 Put 方法,您可以使用以下方法。

The following approach will work for all the type of requests.

以下方法适用于所有类型的请求。

@Configuration
public class CorsConfig implements WebMvcConfigurer {

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

}