2013-04-15 35 views
1

我正在開發一個基於Grails和Vaadin 7的應用程序。我設法讓他們能夠使用SpringSecurity進行身份驗證和授權,但是我必須開發自己的Service來調用Spring Security身份驗證管理器,使其與Vaadin一起工作:SpringSecurity:如何指定記住我的身份驗證?

class SecurityService { 

    static transactional = true 

    def springSecurityService 
    def authenticationManager 

    void signIn(String username, String password) { 
     try { 
      def authentication = new UsernamePasswordAuthenticationToken(username, password) 
      SCH.context.authentication = authenticationManager.authenticate(authentication) 
     } catch (BadCredentialsException e) { 
      throw new SecurityException("Invalid username/password") 
     } 
    } 
} 

問題是,現在我需要實施remember me身份驗證,我不知道從哪裏開始。

如何使authenticationManager知道我希望它使用remeberMeAuthentication?我可以從登錄視圖的複選框中獲得一個布爾值,但接下來我該怎麼處理它呢?

回答

2

由於您的問題是特定於處理來自登錄頁面的複選框值(記住我標誌),答案是您必須致電loginSuccessloginFail方法RememberMeServicesloginSuccess在響應中添加了自動登錄cookie,並且loginFail刪除了該cookie。

但我想上面的答案不會幫助你很多,除非你確定你的應用程序中配置了RememberMeServices。也許下面是配置RememberMeServices步驟將幫助你做整個事情的方式(或幫助您瞭解開箱即用的功能):

(1)創建一個類(稱之爲myRememberMeServices)實現RememberMeServicesLogoutHandler

(2)在autoLogin方法中,在解析cookie值後創建一個認證對象(UsernamePasswordAuthenticationToken)。

(3)在loginFail方法中,取消cookie。

(4)在loginSuccess方法中,創建一個自動登錄cookie。添加您在autoLogin方法中使用的值。通常cookie值是加密的。

(5)在logout方法中,取消cookie。

(6)注射myRememberMeServices在以下四個地方,並調用適當的方法:

(a) At the time of successful login (if checkbox value is set),  
(b) At the time of failed login, 
(c) On logout, and 
(d) In filter that does autologin 

值得注意的是RememberMeAuthenticationFilter需要在其構造authenticationManagerRememberMeServices

回答你的另一個問題是authenticationManager不需要知道記住我的任何事情。它是需要了解authenticationManagerRememberMeServices的過濾器(或處理自動登錄的任何類)。(換句話說,請求RememberMeServices獲取令牌並將其傳遞給authenticationManager以進行自動登錄)。

+1

感謝您的指導。我會盡力深入SpringSecurity和Vaadin。我現在無法檢查你的答案是否已滿,但我想它給出了應該做什麼的概要,所以我會接受它。 – svz

2

Spring Security的架構基於servlet過濾器。您在上面執行的登錄機制通常由UsernamePasswordAuthenticationFilter完成。另一個名爲RememberMeAuthenticationFilter的過濾器負責記住我的功能。 authenticationManager完全不知道應用程序是否使用了記憶我功能。

如果您想將Spring Security與其他Web框架集成,請首先了解兩個框架的過濾器如何一起玩。

+1

嗯,這聽起來不令人鼓舞,但無論如何感謝。 – svz

+2

不要因爲我的回答而氣餒,它可能比看起來更容易做。您只需要很好地理解您使用的框架的架構。爲了全面瞭解Spring Security的基礎架構,我建議您閱讀[參考文檔]的第6,8和9章(http://static.springsource.org/spring-security/site/docs/current/)參考/ springsecurity.html)。它總共有大約20頁的印刷頁面,並不那麼可怕。 – zagyi

+0

謝謝,我會盡力深入SpringSecurity和Vaadin。 – svz

相關問題