2

我在單頁應用程序中使用彈簧引導,彈簧休息和彈簧安全性。spring 4和CSRF

隨着彈簧4,CSRF是默認啓用。

我寫誰延長WebSecurityConfigureAdapter

protected void configure(HttpSecurity http) throws Exception { 
     http.authorizeRequests().antMatchers("/rest/**").authenticated(); 

     http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint); 
     http.formLogin().successHandler(authenticationSuccessHandler); 
     http.formLogin().failureHandler(authenticationFailureHandler); 
     http.logout().logoutSuccessUrl("/"); 

    // tried with and without... same issue 
     http.addFilterAfter(new CsrfTokenResponseHeaderBindingFilter(), CsrfFilter.class); 

} 

CsrfTokenResponseHeaderBindingFilter來自 https://github.com/aditzel/spring-security-csrf-filter/blob/master/src/main/java/com/allanditzel/springframework/security/web/csrf/CsrfTokenResponseHeaderBindingFilter.java

我只用HTML(所以沒有JSP,沒有XHMTL ...)只頁面。 我做ajax調用並餵我的html。

請求頭

POST /login HTTP/1.1 
Host: localhost:8080 
Connection: keep-alive 
Content-Length: 30 
Pragma: no-cache 
Cache-Control: no-cache 
Accept: */* 
Origin: http://localhost:8080 
X-Requested-With: XMLHttpRequest 
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36 
Content-Type: application/x-www-form-urlencoded; charset=UTF-8 
Referer: http://localhost:8080/ 
Accept-Encoding: gzip, deflate 
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4 
Cookie: JSESSIONID=B05ED2676EC1637D74AC7622E018C9FD 

在我的形式,我有

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> 

當我嘗試登錄時,我得到

{"timestamp":1444179957867,"status":403,"error":"Forbidden","message":"Expected CSRF token not found. Has your session expired?","path":"/login"} 

當日志失敗,此命令返回NULL

jqXHR.getResponseHeader('X-CSRF-TOKEN') 

Ajax調用

var data = 'username=' + $('#username').val() + '&password=' + $('#password').val(); 
    $.ajax({ 
    data: data, 
    timeout: 1000, 
    type: 'POST', 
    url: '/login' 
    }).done(function (data, textStatus, jqXHR) { 
    window.location = "main.html"; 
    }).fail(function (jqXHR, textStatus, errorThrown) { 
    }); 
}); 

編輯

在瀏覽器中,當我連接到localhost:8080。

我的頭回答

X-CSRF-HEADER:X-CSRF-TOKEN 
X-CSRF-PARAM:_csrf 
X-CSRF-TOKEN:0d5bf042-a30f-4f2e-a99c-51ed512f811a 

如何讓JS此信息看?我需要把它放在我的電話後。

+0

告訴我們HTTP請求請求 –

+1

你沒有在post –

+0

中發送csrf參數,我想放在那裏? –

回答

0

沒有足夠的信息來調試這個問題。您應該發佈以下信息:

  1. 您的XML/Java Spring安全配置。
  2. 您的Spring Web配置。你在使用JSP還是XHTML?你確定你的視圖模型是正確的嗎?也許你有問題與Web模塊不發送令牌。
  3. 實際的http請求標頭/正文。請求實際上是正確的還是春天只是沒有拿起令牌?