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 作爲表單的隱藏域一起提交即可解決

<!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.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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章