Grails, spring-security-core plugin:使用email登录

来源:互联网 发布:淘宝好评100字通用评论 编辑:程序博客网 时间:2024/06/11 23:49
1. Implement the first requirement – Add an email address property to the user domain 

This is really simple, just add the property to the domain class 

Groovy代码  收藏代码
  1. package org.customauth  
  2.    
  3. class CustomUser {  
  4.    
  5.     String username  
  6.     String password  
  7.     String email  
  8.     boolean enabled  
  9.     boolean accountExpired  
  10.    
  11.     // *******  
  12.     // the rest of the generated class contents  
  13.     // *******  
  14. }  


2. Implement the second requirement – Authenticate using the username or the email 

In order to implement this requirement, I will have to implement a new UserDetailsService 

Groovy代码  收藏代码
  1. package org.customauth  
  2.    
  3. import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUser  
  4. import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUserDetailsService  
  5. import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils  
  6. import org.springframework.security.core.authority.GrantedAuthorityImpl  
  7. import org.springframework.security.core.userdetails.UserDetails  
  8. import org.springframework.security.core.userdetails.UsernameNotFoundException  
  9.    
  10. class CustomUserDetailsService implements GrailsUserDetailsService {  
  11.    
  12.     static final List NO_ROLES = [new GrantedAuthorityImpl(SpringSecurityUtils.NO_ROLE)]  
  13.    
  14.     UserDetails loadUserByUsername(String username, boolean loadRoles)   
  15.     throws UsernameNotFoundException {  
  16.         return loadUserByUsername(username)  
  17.     }  
  18.    
  19.     UserDetails loadUserByUsername(String username)   
  20.     throws UsernameNotFoundException {  
  21.    
  22.         CustomUser.withTransaction { status ->  
  23.             CustomUser user = CustomUser.findByUsernameOrEmail(username, username)  
  24.             if (!user)  
  25.                 throw new UsernameNotFoundException('User not found', username)  
  26.    
  27.             def authorities = user.authorities.collect {  
  28.                 new GrantedAuthorityImpl(it.authority)}  
  29.    
  30.             return new GrailsUser(user.username, user.password, user.enabled,   
  31.             !user.accountExpired, !user.passwordExpired, !user.accountLocked,  
  32.                 authorities ?: NO_ROLES, user.id)  
  33.         }  
  34.     }  
  35. }  


3. With the custom service in place, I need to register it in grails-app/conf/spring/resources.groovy by adding 

Groovy代码  收藏代码
  1. beans = {  
  2.     userDetailsService(org.customauth.CustomUserDetailsService)  
  3. }  


原文:http://mafiadada.iteye.com/blog/1166625