Spring Security 3.2 CSRF 禁用特定 URL

标签 spring spring-mvc spring-security

使用 Spring security 3.2 在我的 Spring MVC 应用程序中启用 CSRF。

我的 spring-security.xml

<http>
 <intercept-url pattern="/**/verify"  requires-channel="https"/>
 <intercept-url pattern="/**/login*"  requires-channel="http"/>
 ...
 ...
 <csrf />
</http>

尝试为请求 URL 中包含“验证”的请求禁用 CSRF。

MySecurityConfig.java

@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

private CsrfMatcher csrfRequestMatcher = new CsrfMatcher();

@Override
public void configure(HttpSecurity http) throws Exception {

    http.csrf().requireCsrfProtectionMatcher(csrfRequestMatcher);

}

class CsrfMatcher implements RequestMatcher {
    @Override
    public boolean matches(HttpServletRequest request) {

        if (request.getRequestURL().indexOf("verify") != -1)
            return false;
        else if (request.getRequestURL().indexOf("homePage") != -1)         
            return false;

        return true;
    }
}

}

Csrf 过滤器验证从“验证”提交的 CSRF token ,并在我从 http 向 https 提交请求时抛出无效 token 异常 (403)。在这种情况下如何禁用 csrf token 身份验证?

最佳答案

我知道这不是一个直接的答案,但人们(如我)在搜索这类问题时通常不会指定 spring 的版本。 所以,自春安a method exists让我们忽略一些路线:

以下将确保 CSRF 保护被忽略:

  1. 任何 GET、HEAD、TRACE、OPTIONS(这是默认设置)
  2. 我们还明确声明忽略任何以“/sockjs/”开头的请求
     http
         .csrf()
             .ignoringAntMatchers("/sockjs/**")
             .and()
         ...

关于Spring Security 3.2 CSRF 禁用特定 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22524470/

相关文章:

java - Spring 安全3.1 : How To Get Security To Kick In At An Alternative Entry Point

java - Spring jpa 禁用合并

java spring jpa使用entityManager.clear()时没有在数据库表中保存任何内容

java - Spring boot postgresql 在安装配置上失败

java - Spring boot 项目生成问题

java - 在 JSP 中按 "Delete"键从服务器端删除 ArrayList 条目

java - 如何将 Spring Security 与 Spring Batch 集成?

java - 使用 Spring Security,管理查询响应授权的正确方法是什么?

spring-mvc - 如何在 Spring MVC 中处理 IO 流

javascript - 如何在 JavaScript 中更改按钮状态