禁用Spring Security for OPTIONS Http Method

Dha*_*ath 66 java spring spring-mvc spring-security cors

是否可以为某种HTTP方法禁用Spring Security?

我们有一个Spring REST应用程序,其服务要求将授权令牌附加到http请求的标头中.我正在为它编写一个JS客户端,并使用JQuery发送GET/POST请求.该应用程序使用此过滤器代码启用CORS.

doFilter(....) {

  HttpServletResponse httpResp = (HttpServletResponse) response;
  httpResp.setHeader("Access-Control-Allow-Origin", "*");
  httpResp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
  httpResp.setHeader("Access-Control-Max-Age", "3600");
  Enumeration<String> headersEnum = ((HttpServletRequest) request).getHeaders("Access-Control-Request-Headers");
  StringBuilder headers = new StringBuilder();
  String delim = "";
  while (headersEnum.hasMoreElements()) {
    headers.append(delim).append(headersEnum.nextElement());
    delim = ", ";
  }
  httpResp.setHeader("Access-Control-Allow-Headers", headers.toString());
}
Run Code Online (Sandbox Code Playgroud)

但是当JQuery发送对CORS的OPTIONS请求时,服务器会使用Authorization Failed令牌进行响应.显然OPTIONS请求缺少授权令牌.那么可以让OPTIONS从Spring安全配置中逃脱安全层吗?

Fel*_*lby 133

如果您使用的是基于注释的安全配置文件(@EnableWebSecurity&@Configuration),则可以在configure()方法中执行以下操作,以允许OPTIONSpring Security在不对给定路径进行身份验证的情况下允许请求:

@Override
protected void configure(HttpSecurity http) throws Exception
{
     http
    .csrf().disable()
    .authorizeRequests()
      .antMatchers(HttpMethod.OPTIONS,"/path/to/allow").permitAll()//allow CORS option calls
      .antMatchers("/resources/**").permitAll()
      .anyRequest().authenticated()
    .and()
    .formLogin()
    .and()
    .httpBasic();
}
Run Code Online (Sandbox Code Playgroud)

  • +1正是我们为启用CORS OPTIONS请求所做的事情。 (2认同)

Luc*_* S. 40

在上下文中允许所有OPTIONS:

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
    }
Run Code Online (Sandbox Code Playgroud)

  • 这似乎是允许OPTIONS请求而无需人工干预的唯一方法。 (3认同)

Koi*_*oer 11

你试过这个吗?

您可以使用多个元素为不同的URL集定义不同的访问要求,但它们将按列出的顺序进行评估,并将使用第一个匹配项.所以你必须把最具体的比赛放在最上面.您还可以添加方法属性以限制与特定HTTP方法(GET,POST,PUT等)的匹配.

<http auto-config="true">
    <intercept-url pattern="/client/edit" access="isAuthenticated" method="GET" />
    <intercept-url pattern="/client/edit" access="hasRole('EDITOR')" method="POST" />
</http>
Run Code Online (Sandbox Code Playgroud)

以上意味着您需要选择要拦截的网址模式以及您想要的方法


won*_*suc 10

不推荐接受的答案,您不应该这样做。
下面是 Spring Security 和 jQuery 的 ajax 的 CORS 设置的正确方法。

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
   
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(userAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors() // <-- This let it use "corsConfigurationSource" bean.
                .and()
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            ...
    }

    @Bean
    protected CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();

        configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000"));
        configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));

        // NOTE: setAllowCredentials(true) is important,
        // otherwise, the value of the 'Access-Control-Allow-Origin' header in the response
        // must not be the wildcard '*' when the request's credentials mode is 'include'.
        configuration.setAllowCredentials(true);

        // NOTE: setAllowedHeaders is important!
        // Without it, OPTIONS preflight request will fail with 403 Invalid CORS request
        configuration.setAllowedHeaders(Arrays.asList(
                "Authorization",
                "Accept",
                "Cache-Control",
                "Content-Type",
                "Origin",
                "x-csrf-token",
                "x-requested-with"
        ));

        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
Run Code Online (Sandbox Code Playgroud)

从 jQuery 方面来看。

$.ajaxSetup({
    // NOTE: Necessary for CORS
    crossDomain: true,
    xhrFields: {
        withCredentials: true
    }
});
Run Code Online (Sandbox Code Playgroud)