2010-10-15 102 views
2

我使用spring創建REST Web服務,並且需要在其中實現登錄/註銷功能。這些函數的url應該是.../api/login和.../api/logout。用戶名和密碼將過去使用POST方法。Spring Security 3以編程方式登錄

我在REST Web服務下面有一個服務層。在服務層,我有「登錄」和「註銷」功能的代碼。我想在spring的上下文中使用spring security來保存登錄的用戶。我找到了幾個答案,但沒有提供完整的例子來說明如何去做。我也想知道使用spring安全性(不使用任何登錄表單,只是程序化登錄/註銷)進行此自定義身份驗證的最新方式。

回答

3

最好的方法是將你的認證實現插入到Spring Security中。 您可以通過在Spring Security中註冊您自己的「身份驗證提供程序」來完成此操作。

例如:

<bean id="authenticationManager" class="org.springframework.security.providers.ProviderManager"> 
    <property name="providers"> 
     <list> 
      <ref local="myAuthenticationProvider"/> 
     </list> 
    </property> 
</bean> 

<bean id="myAuthenticationProvider" class="org.my.web.restapi.authentication.MyAuthenticationProvider"/> 

另一件事:我知道這是一個費時,但看完後Spring Security reference你一定會得到「大畫面」 :-)

0

如果您之後是基本身份驗證經理,下面的代碼將得到它在你的應用,而無需額外的XML配置:如果

@SuppressWarnings({"SpringJavaAutowiringInspection"}) 
@Resource(name = "org.springframework.security.authenticationManager") 
private AuthenticationManager authenticationManager; 
-1

不知道這是你所需要的。 以編程方式調用http://localhost:8080/webappname/j_spring_security_check 在表單參數j_username和j_password中傳遞用戶名密碼。 在安全-APP-context.xml中與

<form-login login-page="/login" login-processing-url="/j_spring_security_check" 
    authentication-success-handler-ref="myAuthenticationSuccessHandler" 
    authentication-failure-handler-ref="myAuthenticationFailureHandler"/> 

<beans:bean id="myAuthenticationSuccessHandler" class="com.something.MyAuthenticationSuccessHandler" /> 
<beans:bean id="myAuthenticationFailureHandler" class="com.something.MyAuthenticationFailureHandler" /> 

替代形式-login元素實現Spring的AuthenticationSuccessHandler和AuthenticationFailureHandler。默認行爲是重定向到登錄表單。