2014-09-06 313 views
-2

我最近在我的spring mvc應用程序中實現了一個文件上傳功能,但不幸的是它不能正常工作,因爲它經常被Spring Security阻止。如果我在安全配置中禁用CSRF,它會起作用,所以它導致我相信在那裏有錯誤。上傳文件被Spring Security拒絕

Spring配置:

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
      .authorizeRequests() 
       .antMatchers("/test/**").permitAll() 
       .antMatchers("/admin/**","/user/secure").hasRole("ADMIN") 
       .antMatchers("/**").permitAll() 
       .anyRequest().anonymous() 
      .and() 
      .exceptionHandling().accessDeniedPage("/denied") 
      .and() 
      .formLogin() 
       .loginPage("/login") 
       .failureUrl("/error-login") 
       .permitAll() 
      .and() 
      .logout() 
       .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) 
       .logoutSuccessUrl("/") 
      .and() 
      .rememberMe() 
       .userDetailsService(userAccessDetails) 
       .tokenRepository(persistentTokenRepository()) 
       .tokenValiditySeconds(16000) 
    ; 
} 

文件上傳表單:

<html xmlns:th="http://www.thymeleaf.org" lang="en"> 
<head> 
    <meta charset="UTF-8"/> 
    <title></title> 
</head> 
<body> 
    <h4>Single File</h4> 
    <form method="POST" th:action="@{/test/uploadFile}" enctype="multipart/form-data"> 
     File to upload: <input type="file" name="file"/><br /> 
     Name: <input type="text" name="name"/><br /> <br /> 
     <input type="submit" value="Upload"/> Press here to upload the file! 
    </form> 
</body> 
</html> 

任何援助,將不勝感激你們。

注:我不得不重新創建了一個問題,原來我錯

+0

爲什麼要投票?這個問題是合法的,並且符合所有必要的標準。 – Aeseir 2014-11-10 00:15:54

回答

1

刪除,你可以做三件事情。

1)實現多節濾波器春天CSRF文檔中提到的(見下面鏈接,更詳細的例子) - http://docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/csrf.html#csrf-multipartfilter

與multipart解析器豆 http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-multipart

沿---差不多這應該除非在上傳過程中涉及更多自定義代碼。如果它有一些定製,那麼選項2更好

2)在config中實現SpringSecurityFilterchain。在安全過濾器開始執行前添加多部分過濾器。實現多部分解析器。

3)沒有任何工作,然後嘗試在客戶端Json轉換文件,並將其作爲二進制數據發佈到服務器。 (它是一種解決方法,並試圖避免這樣做,因爲它不是一個好的設計)。 - 例如pdf2json,你可以使用這個js文件

讓我知道如果任何選項的幫助。

+0

1和2不能正常工作,因爲我試過多種組合。第三個是你說的不是好的設計,我寧願避免。這似乎是一個與彈簧安全 – Aeseir 2014-09-06 07:23:20

+0

如果你有任何3的例子,我可以用它來看看我是否能找到一個適當的修復 – Aeseir 2014-09-06 07:32:52

+0

我想知道你在1和2面臨什麼問題,你可以給更多的細節在上面?對於3有第三方插件爲jQuery,如pdf2json,csvparser等插件如谷歌它的例子,你會得到很多示例代碼在該轉換掛鉤它與您的服務器端調用upload.Mean時間我會做一個工作的例子你並給它你。 – PreTri 2014-09-06 19:28:33