2016-12-02 112 views
2

試圖在最新的Spring Boot上實現CSRF保護。 互聯網上的所有例子都基於用戶登錄和身份驗證,我不需要這些。Spring Boot CSRF

我的網站沒有任何要求驗證的部分。 我想

1) Rest requests come from within site. No direct request from outside with wget to be allowed.

2) All pages (routes) must be requested from the index page (/)

包括在pom.xml

<dependency> 
<groupId>org.springframework.boot</groupId> 
<artifactId>spring-boot-starter-security</artifactId> 
</dependency> 

的安全性依賴 - 定義用戶application.properties(雖然,我並不需要)

- 應用程序創建_csrf.token

- 創建的類擴展WebSecurityConfigurerAdapter與「配置」方法覆蓋。

在「配置」中嘗試了所有建議的過濾器。它沒有工作,最後留下空白。

問題是Wget可以直接獲取api頁面。 如何防止它?

+0

我敢肯定你不能這樣做,你在說什麼這裏沒有一些身份驗證,所以你就必須有隱含的授權。我假設您已閱讀此http://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html以確保事情是正確的。在一個應用程序中,我們必須專門禁用非瀏覽器項目的CSRF,以便它能正常工作。請發佈您認爲應該工作的最佳配置和類。 GitHub的例子可能是最簡單的。 –

回答

1

我趕緊把這個一起配置的POC:

@Configuration 
@EnableWebSecurity 
@SpringBootApplication 
public class StackoverflowQ40929943Application extends WebSecurityConfigurerAdapter{ 

    public static void main(String[] args) { 
     SpringApplication.run(StackoverflowQ40929943Application.class, args); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
       .authorizeRequests() 
        .antMatchers("/**").permitAll(); 
    } 

} 

它的要點是春天引導+安全會自動保護所有的端點。在這裏,我們明確允許所有端點的請求。但是,Spring Boot + Security會自動配置我們啓用的CSRF。因此,你可以得到兩全其美的好處。

注:您可能需要進一步優化此配置以滿足您的需求。

Full Example on GitHub

+0

Tks。測試年代碼。當POST請求直接發送到/端點時,它工作。 正確的,當_csrf字段不包含在POST請求中時,出現錯誤:(status = 403)。 在請求參數'_csrf'或頭部'X-CSRF-TOKEN'上找到無效的CSRF令牌'4afa89cc'。< 但是/端點控制器對沒有控制權的GET請求做出響應。 即使我在請求中添加了錯誤的「X-CSRF-TOKEN」或「_csrf」標頭。 應用程序應直接響應以上錯誤的GET請求,而不是從應用程序內部傳入。 可能在GET URL中添加_csrf或者使用過濾器WebSecurityConfigurerAdapter。 – user3687431

+0

由於GET請求被假定爲只讀,因此無害,因此GET請求不包含在默認的CSRF保護中。正如您所建議的,您可以使用自定義配置添加它。 –