我使用<spring.version>4.2.0.RELEASE</spring.version>
,<spring.security.version>4.0.2.RELEASE</spring.security.version>
和<spring.security.oauth2.version>2.0.9.RELEASE</spring.security.oauth2.version>
。
我使用@CrossOrigin
与CORS一起使用dela。现在,我想允许所有标题和所有方法。我可以使用除授权之外的任何其他标头,而不会出现任何CORS问题。但是使用Authorization(标头发送Bearer令牌),我得到了CORS问题。我在Class级别使用@CrossOrigin
annotatiion并允许所有标题如下 -
@CrossOrigin(allowedHeaders = {"*"})
请求时没有'Access-Control-Allow-Origin'标头 资源
如何允许Authorization标头以及我执行所有其他标头并避免CORS问题?
答案 0 :(得分:1)
您可以将以下内容添加到任何配置文件中:
@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>