Spring Security:按客户端类型启用/禁用CSRF(浏览器/非浏览器)

Him*_*dar 18 java spring spring-mvc csrf spring-security

Spring doc说

"当您使用CSRF保护时?我们的建议是对普通用户可以由浏览器处理的任何请求使用CSRF保护.如果您只创建非浏览器客户端使用的服务,您可能希望禁用CSRF保护."

如果我的服务将被"浏览器"和"非浏览器"客户端(如第三方外部服务)使用,那么Spring安全性是否为某些类型的客户端专门禁用csrf提供了一种方法呢?

参考:http://docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/csrf.html

Him*_*dar 8

我确信有一种方法可以在Spring Security XML中执行此操作,但由于我使用的是Java Config,因此这是我的解决方案.

 @Configuration
 @EnableWebSecurity
 public class SecurityConfig {

    @Configuration
    @Order(1)
    public static class SoapApiConfigurationAdapter extends WebSecurityConfigurerAdapter {
        protected void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/soap/**")
                .csrf().disable()
                .httpBasic();
        }
    }


    @Configuration
    public static class WebApiConfigurationAdapter extends WebSecurityConfigurerAdapter {

        protected void configure(HttpSecurity http) throws Exception {
            http        
                .formLogin()
                    .loginProcessingUrl("/authentication")
                    .usernameParameter("j_username")
                    .passwordParameter("j_password").permitAll()
                    .and()
                .csrf().disable()

        }
     }
}
Run Code Online (Sandbox Code Playgroud)

  • 你不是为所有请求禁用 csrf 吗? (2认同)

Ser*_*sta 5

恕我直言,没有任何东西像开箱即用.在你的情况下,我会做的是拥有一个URL的层次结构,例如,根据/api它的那个将免除csrf.它很容易配置.在XML配置中,您有一个普通的<http>块,包括<csrf/>,您只需复制它并修改第一个块

<http pattern="/api/**">
    ...
    <!-- csrf -->
</http>
Run Code Online (Sandbox Code Playgroud)

首先,它将在/api不使用csrf的情况下触发任何层次结构请求,所有其他请求都将使用它.

在应用程序的正常部分,您永远不会使用该/api/**URL,并将其保留为非浏览器用法.

然后在您的控制器中,将它们映射到它们的正常URL和下面的副本/api:

@Controller
@RequestMapping({ "/rootcontrollerurl", "/api/rootcontrollerurl"})
class XController {
    @RequestMapping(value = "/request_part_url", ...)
    public ModelAndView method() {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

(当然,rootcontrollerurlrequest_part_url可能为空...)

但是,必须分析允许非csrf控制的请求的安全含义,并最终从/api层次结构中排除控制器.