首页 文章

禁用Spring Security for OPTIONS Http Method

提问于
浏览
52

是否可以为某种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());
}

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

4 回答

  • 33

    你试过这个吗?

    您可以使用多个元素为不同的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>
    

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

  • 10

    如果您使用的是基于注释的安全配置文件(@EnableWebSecurity和@Configuration),您可以在configure()方法中执行以下操作,以允许SpringSecurity允许OPTION请求,而无需对给定路径进行身份验证:

    @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();
    }
    
  • 1

    在上下文中允许所有OPTIONS:

    @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
        }
    
  • 106

    如果有人正在寻找使用Spring Boot的简单解决方案 . 只需添加一个额外的bean:

    @Bean
       public IgnoredRequestCustomizer optionsIgnoredRequestsCustomizer() {
          return configurer -> {
             List<RequestMatcher> matchers = new ArrayList<>();
             matchers.add(new AntPathRequestMatcher("/**", "OPTIONS"));
             configurer.requestMatchers(new OrRequestMatcher(matchers));
          };
       }
    

    请注意,根据您的应用程序,这可能会打开它以获取潜在的攻击 .

    打开问题以获得更好的解决方案:https://github.com/spring-projects/spring-security/issues/4448

相关问题