一、问题日志:
HTTP Status 403 - Invalid CSRF Token ‘null’ was found on the request parameter ‘_csrf’ or header ‘X-CSRF-TOKEN’
二、问题原因:
Spring Security 4.0之后,引入了CSRF,默认状态为开启。CSRF和RESTful技术有冲突。CSRF默认支持的方法: GET|HEAD|TRACE|OPTIONS,不支持POST。CSRF(Cross-site request forgery跨站请求伪造,也被称为“One Click Attack” 或者Session Riding,攻击方通过伪造用户请求访问受信任站点。
三、采用的解决办法:
(1)方法一、
修改工程下WebSecurityConfig.java
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(“/”, “/home”).permitAll()
.and()
.formLogin()
.loginPage(“/login”).permitAll()
.and()
.logout().logoutUrl(“/logout”)
.logoutSuccessUrl(“/hello”)
.permitAll();
http.csrf().disable();//在原本的配置文件下添加这行代码,禁用security的csrf
}
(2)方法二、
将http.csrf().disable();注释掉
@Override
protected void configure(HttpSecurity http) throws Exception {
//http.csrf().disable();
http.authorizeRequests()
.antMatchers("/", "/springbootbase").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.permitAll() //5
.and()
.logout().permitAll();
}
将index.html 改成JSP 文件: index.jsp
将csrf token 作为表单的隐藏域一起提交即可解决
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello World</h1>
<form th:action="@{/logout}" action="./logout" method="post">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<input type="submit" value="Sign Out"/>
</form>
</body>
</html>
重启tomcat server, 运行
参考博文:
http://blog.youkuaiyun.com/u012373815/article/details/55047285
http://blog.youkuaiyun.com/ltwang_tech/article/details/55100271?locationNum=7&fps=1
http://blog.youkuaiyun.com/wyccyw123456/article/details/51778398
http://blog.youkuaiyun.com/hong0220/article/details/52922381