你可以通过内置的 CorsFilter 应用 CORS 支持。

:::tips 如果你试图在 Spring Security 中使用 CorsFilter,请记住,Spring Security 对 CORS 有内置支持。 :::

要配置过滤器,请向其构造函数传递一个 CorsConfigurationSource,如下例所示:

  1. CorsConfiguration config = new CorsConfiguration();
  2. // Possibly...
  3. // config.applyPermitDefaultValues()
  4. config.setAllowCredentials(true);
  5. config.addAllowedOrigin("https://domain1.com");
  6. config.addAllowedHeader("*");
  7. config.addAllowedMethod("*");
  8. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  9. source.registerCorsConfiguration("/**", config);
  10. CorsFilter filter = new CorsFilter(source);

如何注册过滤器

这个笔者貌似暂时没有看到官方文档中有过,下面是在 ServletContext 上注册的

  1. package cn.mrcode.study;
  2. import org.springframework.web.WebApplicationInitializer;
  3. import org.springframework.web.context.ContextLoaderListener;
  4. import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
  5. import org.springframework.web.cors.CorsConfiguration;
  6. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  7. import org.springframework.web.filter.CorsFilter;
  8. import org.springframework.web.servlet.DispatcherServlet;
  9. import java.util.EnumSet;
  10. import javax.servlet.DispatcherType;
  11. import javax.servlet.ServletContext;
  12. import javax.servlet.ServletRegistration;
  13. /**
  14. * @author mrcode
  15. */
  16. public class MyWebApplicationInitializer implements WebApplicationInitializer {
  17. @Override
  18. public void onStartup(ServletContext servletContext) {
  19. // 加载 Spring web application configuration
  20. AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
  21. context.register(AppConfig.class);
  22. // Manage the lifecycle of the root application context
  23. servletContext.addListener(new ContextLoaderListener(context));
  24. // 创建和注册 DispatcherServlet
  25. DispatcherServlet servlet = new DispatcherServlet(context);
  26. ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
  27. registration.setLoadOnStartup(1);
  28. registration.addMapping("/");
  29. registration.setAsyncSupported(true);
  30. CorsConfiguration config = new CorsConfiguration();
  31. // Possibly...
  32. // config.applyPermitDefaultValues()
  33. config.setAllowCredentials(true);
  34. config.addAllowedOrigin("*");
  35. config.addAllowedHeader("*");
  36. config.addAllowedMethod("*");
  37. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  38. source.registerCorsConfiguration("/**", config);
  39. CorsFilter filter = new CorsFilter(source);
  40. servletContext.addFilter("CorsFilter",filter)
  41. // 这里配置的是,过滤器在哪些类型上进行拦截,这里选择 request ,并对 app 这个 servlet 进行拦截
  42. // 因为所有的请求都是 DispatcherServlet 接管的,所以只要拦截它就可以实现全局配置了
  43. .addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST),true,"app");
  44. }
  45. }