HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf'...

一、问题日志:
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 作为表单的隐藏域一起提交即可解决


<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 Worldh1>
    <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.csdn.net/u012373815/article/details/55047285
http://blog.csdn.net/ltwang_tech/article/details/55100271?locationNum=7&fps=1
http://blog.csdn.net/wyccyw123456/article/details/51778398
http://blog.csdn.net/hong0220/article/details/52922381

你可能感兴趣的:(Java)