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

Spring doc说

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

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

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

我确信有一种方法可以在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() } } } 

恕我直言,没有任何开箱即用的东西 。 在我的情况下,我会做的是拥有一个URL层次结构,例如以/api为根,可以免除csrf。 它易于配置。 在XML配置中,你有一个普通的块,包括 ,你只需复制它并修改第一个块就像那样

  ...   

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

在应用程序的正常部分,您永远不会使用/api/** url,并将它们保留给非浏览器用法。

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

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

(当然, rootcontrollerurlrequest_part_url可能是空白的……)

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

以下是我在appconfig-security.xml上的特定端点上禁用CSRF保护的内容,添加一个包含模式信息的节点,如下例所示:

    

请记住,如果您要使用地图所有请求,请先使用符号’*’,顺序很重要。