2013-12-19 120 views
2

,因爲我已經在我的Grails應用程序中使用一個專門的服務,使認證通過一個vaadin UI,我是有問題,驗證登錄工作過:Grails的Spring Security認證

1 )一個新的用戶在自舉創建和記錄到分貝(postgre)

User.withTransaction { 
    User test = new User(
     username: "test", 
     password: springSecurityService.encodePassword("password"), 
     enabled: true, 
     accountExpired: false, 
     accountLocked: false, 
     passwordExpired: false 
    ).save() 

Role dashManager = new Role(authority: "ROLE_USER").save() 

new UserRole(user: test, role: dashManager).save() 

2)vaadin UI通常調用的grails服務

boolean login(String username, String password) { 
    try { 
     println username + "----" + password 
     security.signIn(username, password) 
     return true 
    } catch (SecurityServiceException e) { 
     Notification.show("Login/Password incorrect", Notification.TYPE_ERROR_MESSAGE); 
     return false 
    } 
} 

3)我securityService總是重新變成無效

import grails.transaction.Transactional 
import org.springframework.security.core.context.SecurityContextHolder as SCH 
import org.springframework.security.authentication.BadCredentialsException 
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken 

@Transactional 
class SecurityService { 

    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") 
     } 
    } 

    void signOut() { 
     SCH.context.authentication = null 
    } 

    boolean isSignedIn() { 
     return springSecurityService.isLoggedIn() 
    } 
} 

回答

3

您可能是雙重編碼密碼。最近版本的插件生成一個用戶/人員域類,它爲您編碼密碼,因此您不需要撥打springSecurityService.encodePassword("password"),如果您這樣做,那麼它將被編碼兩次。這應該工作:

User test = new User(
    username: "test", 
    password: "password", 
    enabled: true 
).save() 

我省略設置accountExpiredaccountLocked,並passwordExpiredfalse這是因爲它們的默認值。

+0

感謝伯特,你做了我的 –

0

使用springSecurityService驗證

void signIn(String username, String password) { 
     try { 
      springSecurityService.reauthenticate(username, password) 
     } catch (BadCredentialsException e) { 
      throw new SecurityException("Invalid username/password") 
     } 
    } 
+4

一天只有當你想在一個已知良好的認證強制使用'reauthenticate'。此方法的主要用途是在更新數據庫之後更新身份驗證,以確保內存中的數據同步(因此名稱 - 它是'reauthenticate',而不是'authenticate')。但是,如果你想實際驗證密碼,請檢查用戶是否被鎖定等,然後使用'ProviderManager'('authenticationManager' bean)進行正確驗證是必要的。 –

+0

當我使用「摘要」身份驗證時,我已經實現了上述服務以確保獲得令牌...無論如何,我錯過了已經移動到最後版本的域類的encodePassword()(即beforeInsert )) –