2011-09-27 61 views
0

我正在使用帶有REST端點的Spring Security 3。我設法讓基本的Spring Security工作。Spring Security 3 Rest模板POST到j_spring_security_check

與安全的context.xml

<security:http auto-config="true" use-expressions="true" access-denied-page="/rest/denied" > 
<security:intercept-url pattern="/rest/*" access="ROLE_USER"/> 

和基本配置的一部分,網絡上的發現

<security:authentication-manager> 
     <security:authentication-provider user-service-ref="userDetailsService"> 
      <security:password-encoder ref="passwordEncoder"/> 
    </security:authentication-provider> 

<!-- Use a Md5 encoder since the user's passwords are stored as Md5 in the database --> 
<bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/> 

<!-- An in-memory list of users. No need to access an external database layer. 
See Spring Security 3.1 Reference 5.2.1 In-Memory Authentication --> 
    <!-- john's password is admin, while jane;s password is user --> 
    <security:user-service id="userDetailsService"> 
    <security:user name="john" password="21232f297a57a5a743894a0e4a801fc3"  authorities="ROLE_USER, ROLE_ADMIN" /> 
    <security:user name="jane" password="ee11cbb19052e40b07aac0ca060c23ee" authorities="ROLE_USER" /> 
</security:user-service> 

我想登錄使用RestTemplate到j_spring_security_check POST。

HttpEntity<String> entity = new HttpEntity<String>(request, headers); 
      HashMap<String, String> map = new HashMap<String, String>(); 
      map.put("j_username", "john"); 
      map.put("j_password","21232f297a57a5a743894a0e4a801fc3"); 

      String response = restTemplate.postForObject("http://localhost:8080/rest/j_spring_security_check", map, String.class); 

但在日誌中,似乎username參數沒有被讀取

DEBUG o.s.s.authentication.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider 
DEBUG o.s.s.a.d.DaoAuthenticationProvider - User '' not found 
DEBUG o.s.s.w.a.UsernamePasswordAuthenticationFilter - Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials 

什麼是讓REST模板發佈身份驗證憑據正確的方法是什麼?有沒有更好的方式登錄/獲得授權,而不是j_spring_security_check?信息是否在標題中?

在此先感謝。

回答

1

這看起來像是another SO question的副本。不過,你可能正在接近這個錯誤的方式。通常,如果你發出一個REST請求你不會在同一時間被驗證 - 這沒有任何意義 - 肯定不使用表單POST風格邏輯。

休息的身份驗證請求,你應該使用的身份驗證的另一種形式(假設這些請求程序生成): * HTTP基本驗證 * X.509證書

或者如果這是通過XHR發生/ JavaScript的起源,你應該準備有請求失敗,將用戶重定向到登錄機制。通常使用Spring Security處理REST樣式請求與處理常規受保護頁面完全不同。你應該準備一些複雜性。

祝你好運!

+0

感謝您的答覆,我也看看其他職位,也許我可以嘗試,並採取他們的做法。我會看看X.509,它可能運作良好。 – devl