您可以将以下内容添加到任何配置文件中:
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
编辑
对于 XML 配置,您可以创建一个自定义过滤器并将其添加到您的过滤器链中:
public class CorsFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "*");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
XML 配置
<security:filter-chain-map>
<sec:filter-chain pattern="/**"
filters="
ConcurrentSessionFilterAdmin,
securityContextPersistenceFilter,
logoutFilterAdmin,
usernamePasswordAuthenticationFilterAdmin,
basicAuthenticationFilterAdmin,
requestCacheAwareFilter,
securityContextHolderAwareRequestFilter,
anonymousAuthenticationFilter,
sessionManagementFilterAdmin,
exceptionTranslationFilter,
filterSecurityInterceptorAdmin,
CorsFilter"/>
</security:filter-chain-map>