问题描述
我用Spring安全性在Spring Boot中开发Web应用程序。
这是我用于实现csrf的代码
配置类。...
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity security) throws Exception {
// Todo Auto-generated method stub
security.httpBasic().disable();
security.authorizeRequests()
.antMatchers("/DDR/**").permitAll()
.antMatchers("/assets/**").permitAll();
}
}
在JSP中添加了以下注释
<Meta name="_csrf" content="${_csrf.token}" />
<Meta name="_csrf_header" content="${_csrf.headerName}" />
获取js中的值
var token = $("Meta[name='_csrf']").attr("content");
var header = $("Meta[name='_csrf_header']").attr("content");
最后在Ajax请求中添加了标头
headers : {
"X-CSRF-TOKEN" : token
},
我们是否需要在服务器端(java端)进行任何其他编码来验证CSRF?或者Spring Security将处理该代码?预先感谢。
解决方法
一切似乎都正确。默认情况下,使用Java配置会启用CSRF保护。为了确保一切正常,您可以检查每个发送csrf标头值的请求。另外,您应该尝试对应用程序进行csrf攻击以进行测试。您可以创建一个虚拟应用程序,该应用程序调用post api并在虚拟应用程序中检查响应。如果一切配置正确,则应返回403。