你可以通过内置的 CorsFilter 应用 CORS 支持。
:::tips 如果你试图在 Spring Security 中使用 CorsFilter,请记住,Spring Security 对 CORS 有内置支持。 :::
要配置过滤器,请向其构造函数传递一个 CorsConfigurationSource,如下例所示:
CorsConfiguration config = new CorsConfiguration();// Possibly...// config.applyPermitDefaultValues()config.setAllowCredentials(true);config.addAllowedOrigin("https://domain1.com");config.addAllowedHeader("*");config.addAllowedMethod("*");UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", config);CorsFilter filter = new CorsFilter(source);
如何注册过滤器
这个笔者貌似暂时没有看到官方文档中有过,下面是在 ServletContext 上注册的
package cn.mrcode.study;import org.springframework.web.WebApplicationInitializer;import org.springframework.web.context.ContextLoaderListener;import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;import org.springframework.web.filter.CorsFilter;import org.springframework.web.servlet.DispatcherServlet;import java.util.EnumSet;import javax.servlet.DispatcherType;import javax.servlet.ServletContext;import javax.servlet.ServletRegistration;/*** @author mrcode*/public class MyWebApplicationInitializer implements WebApplicationInitializer {@Overridepublic void onStartup(ServletContext servletContext) {// 加载 Spring web application configurationAnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();context.register(AppConfig.class);// Manage the lifecycle of the root application contextservletContext.addListener(new ContextLoaderListener(context));// 创建和注册 DispatcherServletDispatcherServlet servlet = new DispatcherServlet(context);ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);registration.setLoadOnStartup(1);registration.addMapping("/");registration.setAsyncSupported(true);CorsConfiguration config = new CorsConfiguration();// Possibly...// config.applyPermitDefaultValues()config.setAllowCredentials(true);config.addAllowedOrigin("*");config.addAllowedHeader("*");config.addAllowedMethod("*");UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/**", config);CorsFilter filter = new CorsFilter(source);servletContext.addFilter("CorsFilter",filter)// 这里配置的是,过滤器在哪些类型上进行拦截,这里选择 request ,并对 app 这个 servlet 进行拦截// 因为所有的请求都是 DispatcherServlet 接管的,所以只要拦截它就可以实现全局配置了.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST),true,"app");}}
