Java Spring 安全 CORS 过滤器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40418441/
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
Spring security CORS Filter
提问by M. Thiele
We added Spring Security
to our existing project.
我们添加Spring Security
到我们现有的项目中。
From this moment on we get a 401 No 'Access-Control-Allow-Origin' header is present on the requested resource
error from the our server.
从这一刻起,我们No 'Access-Control-Allow-Origin' header is present on the requested resource
从我们的服务器收到 401错误。
That's because no Access-Control-Allow-Origin
header is attached to the response. To fix this we added our own filter which is in the Filter
chain before the logout filter, but the filter does not apply for our requests.
那是因为没有Access-Control-Allow-Origin
标题附加到响应。为了解决这个问题,我们Filter
在注销过滤器之前的链中添加了我们自己的过滤器,但过滤器不适用于我们的请求。
Our Error:
我们的错误:
XMLHttpRequest cannot load
http://localhost:8080/getKunden
. No 'Access-Control-Allow-Origin' header is present on the requested resource. Originhttp://localhost:3000
is therefore not allowed access. The response had HTTP status code 401.
XMLHttpRequest 无法加载
http://localhost:8080/getKunden
。请求的资源上不存在“Access-Control-Allow-Origin”标头。http://localhost:3000
因此不允许访问Origin 。响应的 HTTP 状态代码为 401。
Our Security configuration:
我们的安全配置:
@EnableWebSecurity
@Configuration
@ComponentScan("com.company.praktikant")
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private MyFilter filter;
@Override
public void configure(HttpSecurity http) throws Exception {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
source.registerCorsConfiguration("/**", config);
http.addFilterBefore(new MyFilter(), LogoutFilter.class).authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/*").permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
}
}
Our filter
我们的过滤器
@Component
public class MyFilter extends OncePerRequestFilter {
@Override
public void destroy() {
}
private String getAllowedDomainsRegex() {
return "individual / customized Regex";
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
final String origin = "http://localhost:3000";
response.addHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers",
"content-type, x-gwt-module-base, x-gwt-permutation, clientid, longpush");
filterChain.doFilter(request, response);
}
}
Our Application
我们的应用
@SpringBootApplication
public class Application {
public static void main(String[] args) {
final ApplicationContext ctx = SpringApplication.run(Application.class, args);
final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
annotationConfigApplicationContext.register(CORSConfig.class);
annotationConfigApplicationContext.refresh();
}
}
Our filter is registered from spring-boot:
我们的过滤器是从 spring-boot 注册的:
2016-11-04 09:19:51.494 INFO 9704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'myFilter' to: [/*]
2016-11-04 09:19:51.494 INFO 9704 --- [ost-startStop-1] osbwservlet.FilterRegistrationBean:映射过滤器:'myFilter'到:[/*]
Our generated filterchain:
我们生成的过滤器链:
2016-11-04 09:19:52.729 INFO 9704 --- [ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@5d8c5a8a, org.springframework.security.web.context.SecurityContextPersistenceFilter@7d6938f, org.springframework.security.web.header.HeaderWriterFilter@72aa89c, org.springframework.security.web.csrf.CsrfFilter@4af4df11, com.company.praktikant.MyFilter@5ba65db2, org.springframework.security.web.authentication.logout.LogoutFilter@2330834f, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@396532d1, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@4fc0f1a2, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@2357120f, org.springframework.security.web.session.SessionManagementFilter@10867bfb, org.springframework.security.web.access.ExceptionTranslationFilter@4b8bf1fb, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@42063cf1]
2016-11-04 09:19:52.729 INFO 9704 --- [ost-startStop-1] ossweb.DefaultSecurityFilterChain:创建过滤器链:org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework .security.web.context.request.async.WebAsyncManagerIntegrationFilter@5d8c5a8a, org.springframework.security.web.context.SecurityContextPersistenceFilter@7d6938f, org.springframework.security.web.header.HeaderWriterFilter@72aa89c, org.springframework.security.web .csrf.CsrfFilter@4af4df11、com.company.praktikant.MyFilter@5ba65db2、org.springframework.security.web.authentication.logout.LogoutFilter@2330834f、org.springframework.security.web.savedrequest.RequestCacheAware2orgframed19 .security.web.servletapi.SecurityContextHolderAwareRequestFilter@4fc0f1a2,org.springframework.security.web.authentication。AnonymousAuthenticationFilter@2357120f,org.springframework.security.web.session.SessionManagementFilter@10867bfb,org.springframework.security.web.access.ExceptionTranslationFilter@4b8bf1fb,org.springframework.security.web.access.intercept.FilterSecurityInterceptor@41206]c
The Response: Response headers
响应: 响应头
We tried the solution from spring as well but it didn't work! The annotation @CrossOrigin in our controller didn't help either.
我们也尝试了 spring 的解决方案,但没有奏效!我们控制器中的 @CrossOrigin 注释也没有帮助。
Edit 1:
编辑1:
Tried the solution from @Piotr So?tysiak. The cors filter isn't listed in the generated filter chain and we still get the same error.
尝试了@Piotr So?tysiak 的解决方案。cors 过滤器未列在生成的过滤器链中,我们仍然遇到相同的错误。
2016-11-04 10:22:49.881 INFO 8820 --- [ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@4c191377, org.springframework.security.web.context.SecurityContextPersistenceFilter@28bad32a, org.springframework.security.web.header.HeaderWriterFilter@3c3ec668, org.springframework.security.web.csrf.CsrfFilter@288460dd, org.springframework.security.web.authentication.logout.LogoutFilter@1c9cd096, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@3990c331, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@1e8d4ac1, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@2d61d2a4, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@380d9a9b, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@abf2de3, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@2a5c161b, org.springframework.security.web.session.SessionManagementFilter@3c1fd3e5, org.springframework.security.web.access.ExceptionTranslationFilter@3d7055ef, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@5d27725a]
2016-11-04 10:22:49.881 INFO 8820 --- [ost-startStop-1] ossweb.DefaultSecurityFilterChain:创建过滤器链:org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework .security.web.context.request.async.WebAsyncManagerIntegrationFilter@4c191377, org.springframework.security.web.context.SecurityContextPersistenceFilter@28bad32a, org.springframework.security.web.header.HeaderWriterFilter@3c3ec668, org.springframework.security.web .csrf.CsrfFilter@288460dd, org.springframework.security.web.authentication.logout.LogoutFilter@1c9cd096, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@3990c331, org.springframework.security.webrating.authentication.logout.LogoutFilter@1c9cd096 @1e8d4ac1,org.springframework.security.web.authentication.www.BasicAuthenticationFilter@2d61d2a4,组织。springframework.security.web.savedrequest.RequestCacheAwareFilter@380d9a9b,org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@abf2de3,org.springframework.security.web.authentication.AnonymousAuthenticationFilter@2a5c161b,org.springframework.security. SessionManagementFilter@3c1fd3e5,org.springframework.security.web.access.ExceptionTranslationFilter@3d7055ef,org.springframework.security.web.access.intercept.FilterSecurityInterceptor@5d27725a]access.ExceptionTranslationFilter@3d7055ef, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@5d27725a]access.ExceptionTranslationFilter@3d7055ef, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@5d27725a]
Btw we are using spring-security version 4.1.3.!
顺便说一句,我们使用的是 spring-security 版本 4.1.3。!
采纳答案by M. Thiele
Ok, after over 2 days of searching we finally fixed the problem. We deleted all our filter and configurations and instead used this 5 lines of code in the application class.
好的,经过 2 天多的搜索,我们终于解决了问题。我们删除了所有过滤器和配置,而是在应用程序类中使用了这 5 行代码。
@SpringBootApplication
public class Application {
public static void main(String[] args) {
final ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000");
}
};
}
}
回答by Piotr So?tysiak
You don't need:
@Configuration @ComponentScan("com.company.praktikant")
@EnableWebSecurity
already has@Configuration
in it, and I cannot imagine why you put@ComponentScan
there.About CORS filter, I would just put this:
@Bean public FilterRegistrationBean corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); bean.setOrder(0); return bean; }
Into SecurityConfiguration class and remove configure and configure global methods. You don't need to set allowde orgins, headers and methods twice. Especially if you put different properties in filter and spring security config :)
According to above, your "MyFilter" class is redundant.
You can also remove those:
final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(); annotationConfigApplicationContext.register(CORSConfig.class); annotationConfigApplicationContext.refresh();
From Application class.
At the end small advice - not connected to the question. You don't want to put verbs in URI. Instead of
http://localhost:8080/getKunden
you should use HTTP GET method onhttp://localhost:8080/kunden
resource. You can learn about best practices for design RESTful api here: http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api
你不需要:
@Configuration @ComponentScan("com.company.praktikant")
@EnableWebSecurity
已经@Configuration
在里面了,我无法想象你为什么把@ComponentScan
它放在那里。关于 CORS 过滤器,我只想说:
@Bean public FilterRegistrationBean corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); bean.setOrder(0); return bean; }
进入 SecurityConfiguration 类并删除 configure 和 configure 全局方法。您不需要两次设置允许的来源、标题和方法。特别是如果您在过滤器和弹簧安全配置中放置了不同的属性:)
根据上文,您的“MyFilter”类是多余的。
您还可以删除那些:
final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(); annotationConfigApplicationContext.register(CORSConfig.class); annotationConfigApplicationContext.refresh();
从应用程序类。
最后的小建议 - 与问题无关。您不想将动词放在 URI 中。而不是
http://localhost:8080/getKunden
您应该对http://localhost:8080/kunden
资源使用 HTTP GET 方法。您可以在此处了解设计 RESTful api 的最佳实践:http: //www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api
回答by Alex Fernandez
In my case, I just added this class and use @EnableAutConfiguration
就我而言,我只是添加了这个类并使用了 @EnableAutConfiguration
package com.package.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class SimpleCORSFilter extends GenericFilterBean {
/**
* The Logger for this class.
*/
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
logger.info("> doFilter");
HttpServletResponse response = (HttpServletResponse) resp;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
//response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, resp);
logger.info("< doFilter");
}
}
}
回答by Hendy Irawan
Since Spring Security 4.1, this is the proper way to make Spring Security support CORS (also needed in Spring Boot 1.4/1.5):
从 Spring Security 4.1 开始,这是使 Spring Security 支持 CORS 的正确方法(Spring Boot 1.4/1.5 中也需要):
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
}
and:
和:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// http.csrf().disable();
http.cors();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(ImmutableList.of("*"));
configuration.setAllowedMethods(ImmutableList.of("HEAD",
"GET", "POST", "PUT", "DELETE", "PATCH"));
// setAllowCredentials(true) is important, otherwise:
// The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
configuration.setAllowCredentials(true);
// setAllowedHeaders is important! Without it, OPTIONS preflight request
// will fail with 403 Invalid CORS request
configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
Do notdo any of below, which are the wrong way to attempt solving the problem:
千万不能做任何的下方,这是错误的方式来尝试解决问题:
http.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll();
web.ignoring().antMatchers(HttpMethod.OPTIONS);
http.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll();
web.ignoring().antMatchers(HttpMethod.OPTIONS);
Reference: http://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/cors.html
参考:http: //docs.spring.io/spring-security/site/docs/4.2.x/reference/html/cors.html
回答by David Eibensteiner
Since i had problems with the other solutions (especially to get it working in all browsers, for example edge doesn't recognize "*" as a valid value for "Access-Control-Allow-Methods"), i had to use a custom filter component, which in the end worked for me and did exactly what i wanted to achieve.
由于我在使用其他解决方案时遇到了问题(特别是为了让它在所有浏览器中工作,例如 edge 无法将“*”识别为“Access-Control-Allow-Methods”的有效值),我不得不使用自定义filter 组件,它最终对我有用,并且完全符合我想要实现的目标。
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods",
"ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Key, Authorization");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
public void init(FilterConfig filterConfig) {
// not needed
}
public void destroy() {
//not needed
}
}
回答by lmiguelmh
According the CORS filter documentation:
根据CORS 过滤器文档:
"Spring MVC provides fine-grained support for CORS configuration through annotations on controllers. However when used with Spring Security it is advisable to rely on the built-in CorsFilterthat must be ordered ahead of Spring Security's chain of filters"
“Spring MVC 通过控制器上的注释为 CORS 配置提供了细粒度的支持。但是,当与 Spring Security 一起使用时,建议依赖必须在 Spring Security 的过滤器链之前订购的内置 CorsFilter”
Something like this will allow GET
access to the /ajaxUri
:
这样的事情将允许GET
访问/ajaxUri
:
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Arrays;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class AjaxCorsFilter extends CorsFilter {
public AjaxCorsFilter() {
super(configurationSource());
}
private static UrlBasedCorsConfigurationSource configurationSource() {
CorsConfiguration config = new CorsConfiguration();
// origins
config.addAllowedOrigin("*");
// when using ajax: withCredentials: true, we require exact origin match
config.setAllowCredentials(true);
// headers
config.addAllowedHeader("x-requested-with");
// methods
config.addAllowedMethod(HttpMethod.OPTIONS);
config.addAllowedMethod(HttpMethod.GET);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/startAsyncAuthorize", config);
source.registerCorsConfiguration("/ajaxUri", config);
return source;
}
}
Of course, your SpringSecurity configuration must allow access to the URI with the listed methods. See @Hendy Irawan answer.
当然,您的 SpringSecurity 配置必须允许使用列出的方法访问 URI。请参阅@Hendy Irawan 的回答。
回答by Garik Kalashyan
In many places, I see the answer that needs to add this code:
很多地方看到需要加这段代码的答案:
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
but in my case, it throws an unexpected class type exception. corsFilter()
bean requires CorsFilter
type, so I have done this changes and put this definition of bean in my config and all is OK now.
但就我而言,它引发了意外的类类型异常。corsFilter()
bean 需要CorsFilter
类型,所以我已经完成了这些更改并将 bean 的这个定义放在我的配置中,现在一切正常。
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
回答by Grigory Kislin
With Spring Security in Spring Boot 2 to configure CORS globally (e.g. enabled all request for development) you can do:
使用 Spring Boot 2 中的 Spring Security 全局配置 CORS(例如启用所有开发请求),您可以执行以下操作:
@Bean
protected CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and().authorizeRequests()
.anyRequest().permitAll()
.and().csrf().disable();
}
回答by mikejones1477
There's 8 hours of my life I will never get back...
我生命中的 8 个小时我永远不会回来......
Make sure that you set both Exposed Headers AND Allowed Headers in your CorsConfiguration
确保在 CorsConfiguration 中设置了 Exposed Headers 和 Allowed Headers
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
configuration.setAllowedMethods(Arrays.asList("GET","POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
configuration.setExposedHeaders(Arrays.asList("Authorization", "content-type"));
configuration.setAllowedHeaders(Arrays.asList("Authorization", "content-type"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
回答by Theo Dury
This solution unlock me after couple of hours of research :
经过几个小时的研究,这个解决方案让我解锁:
In the configuration initialize the core() option
在配置中初始化 core() 选项
@Override
public void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.etc
}
Initialize your Credential, Origin, Header and Method as your wish in the corsFilter.
在 corsFilter 中按照您的意愿初始化您的 Credential、Origin、Header 和 Method。
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new
UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
I didn't need to use this class:
我不需要使用这个类:
@Bean
public CorsConfigurationSource corsConfigurationSource() {
}