Spring Security 3.2 CSRF禁用特定的URL [英] Spring Security 3.2 CSRF disable for specific URLs

查看:595
本文介绍了Spring Security 3.2 CSRF禁用特定的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Spring Security 3.2在我的Spring MVC应用程序中启用了CSRF.

Enabled CSRF in my Spring MVC application using Spring security 3.2.

我的spring-security.xml

My spring-security.xml

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

尝试对请求URL中包含验证"的请求禁用CSRF.

Trying to disable CSRF for requests that contain 'verify' in request URL.

MySecurityConfig.java

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令牌,并且当我从http向https提交请求时引发了无效令牌异常(403).在这种情况下如何禁用csrf令牌认证?

Csrf filter validates CSRF token that is submitted from 'verify' and Invalid token exception (403) is thrown as I'm submitting request to https from http. How can I disable csrf token authentication in such a scenario ?

推荐答案

我知道这不是直接答案,但是人们(像我一样)在搜索此类问题时通常不指定spring的版本. 因此,由于spring security

I know this is not a direct answer, but people (as me) usually don't specify spring's version when searching for this kinds of questions. So, since spring security a method exists that lets ignore some routes:

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

The following will ensure CSRF protection ignores:

  1. 任何GET,HEAD,TRACE,OPTIONS(这是默认设置)
  2. 我们还明确声明忽略任何以"/sockjs/"开头的请求


     http
         .csrf()
             .ignoringAntMatchers("/sockjs/**")
             .and()
         ...

这篇关于Spring Security 3.2 CSRF禁用特定的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆