使用 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 保护被忽略:
- 任何 GET、HEAD、TRACE、OPTIONS(这是默认设置)
- 我们还明确声明忽略任何以“/sockjs/”开头的请求
http .csrf() .ignoringAntMatchers("/sockjs/**") .and() ...
关于Spring Security 3.2 CSRF 禁用特定 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22524470/