2

我使用<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。现在,我想允许所有标题和所有方法。我可以使用除 Authorization 之外的任何其他标头,而不会出现任何 CORS 问题。但是使用授权(发送不记名令牌的标头),我得到了 CORS 问题。我@CrossOrigin在类级别使用注释并允许所有标题如下 -

@CrossOrigin(allowedHeaders = {"*"})

请求的资源上不存在“Access-Control-Allow-Origin”标头

我如何允许 Authorization 标头以及所有其他标头并避免 CORS 问题?

4

1 回答 1

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>
于 2016-03-11T00:40:18.350 回答