[英]How to disable CORS in Spring Security within Spring Boot?
我想使用 Spring 安全性从 Spring 引导(2.3.3.RELEASE)中完全删除 CORS。
HttpSecurity
object 有WebSecurityConfigurerAdapter#configure
方法,我可以在其中调用cors().disable()
但它似乎不起作用。
class MySecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().disable();
}
}
使用上面的代码段,在从我的前端应用程序访问端点时,我仍然会收到 CORS 错误。
相反,我必须从WebMvcConfigurer
界面覆盖addCorsMappings
,如下所示。
这是为什么? 为什么调用http.cors().disable()
是不够的?
class MySecurityConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*")
.allowedOrigins("*");
}
您好,您需要在 spring 引导项目中创建一个全局 cors 配置。创建一个 class 并使用 @Configuration 对其进行注释。 您可以按照下面的示例进行操作。
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}
};
}
}
这是 spring 框架提供的完整指南https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.