2016-08-13 149 views
2

我正在嘗試在Spring Boot API上構建一個Angular 2頁面。我已經配置了CORS(正確的我相信),但是我被Spring Security的CSRF保護阻止了。Angular 2/Spring Security CSRF實現問題

這是我的理解,Angular2自動處理RC2的RCF,我在RC4上。服務器響應來自客戶端的POST發送XSRF令牌在這裏看到:

我認爲角2不撿起來?我知道CORS正在工作,因爲當我在.csrf()的末尾放.ignoringAntMatchers(「/ urlhere /」)進行測試時,請求已經完成,因此CORS不會阻止它。這裏是我的HttpSecurity配置方法:

@Override 
protected void configure(HttpSecurity http) throws Exception { 

    http 
     .authorizeRequests() 
      .antMatchers("/auth/**", "/signup/**").permitAll() 
      .and() 
     .headers() 
      .and() 
     .exceptionHandling() 
      .and() 
     .cors() 
      .and() 
     .csrf() 
      .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); 

} 

我的登錄信息在客戶端過程包括,首先發送證書的方法,然後使用JWT令牌來獲取證書。兩種方法如下:

sendCredentials(model) { 
    let tokenUrl = 'http://localhost:8080/user/login'; 
    let headers1 = new Headers({'Content-Type': 'application/json'}); 

    return this.http.post(tokenUrl, JSON.stringify(model), {headers: headers1}); 
} 

sendToken(token){ 
    let userUrl = 'http://localhost:8080/rest/user/users'; 
    let headers2 = new Headers({'Authorization': 'Bearer '+token}); 

    return this.http.get(userUrl, {headers:headers2}); 
} 

我缺少什麼來滿足CSRF保護的要求?它是客戶端嗎?或者我需要將/login/添加到我的antMatchers列表中?

回答

1

我知道這是晚了,但是,我遇到了同樣的問題,並設法解決它。 問題的角度http請求:

return this.http.post(tokenUrl, JSON.stringify(model), {headers: headers1}); 

您需要調整它來發送這樣的:

return this.http.post(tokenUrl, JSON.stringify(model), {headers: headers1, withCredentials: true}); 

您必須添加withCredentials: true到您的所有HTTP請求。 爲什麼你需要它?每次向Spring(服務器)發送http請求(OPTIONS,POST等)時,它都會生成新的XSRF-TOKEN並將其發送給客戶端,withCredentials: true將在瀏覽器中保存這個新的XSRF-TOKEN,之後用於新的http請求,所以如果您的某個http請求沒有withCredentials: true,它將簡單地忽略新的XSRF-TOKEN,並對http請求使用舊的(過期的)XSRF-TOKEN。

+0

感謝您的回答!它增加了知識庫,所以我將其標記爲已回答。 –