1. 程式人生 > >Invalid CSRF Token 'null' was found on the request parameter '_csrf'...

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, 執行