これに関しては最近のものではないと思います。spring security/grails 3.2.8 以降のバージョン。これが私のものです:
これはサービスで作成されたサービスです。ユーザーの電子メールは User の外部の別のクラスにあるため、attributes.email
そうでない場合はチェックを実行できますUser.findByUsernameOrEmail(username,username)
だから私は UserEmailUserService をサービスとして持っています:
package com.app.users
import grails.plugin.springsecurity.userdetails.GormUserDetailsService
import grails.transaction.Transactional
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UsernameNotFoundException
class UserEmailUserService extends GormUserDetailsService{
UserDetails loadUserByUsername(String username, boolean loadRoles)
throws UsernameNotFoundException {
return loadUserByUsername(username)
}
@Transactional
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//enable login with either username or password
User user = User.find {
username == username || attributes.email == username
}
if (!user) throw new UsernameNotFoundException('User not found', username)
UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.username, user.getPassword(),
user.enabled, !user.accountExpired, !user.passwordExpired, !user.accountLocked, getAuthorities(user.roles))
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities())
SecurityContextHolder.getContext().setAuthentication(authentication);
return userDetails
}
public static List<GrantedAuthority> getAuthorities(Set<Role> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>()
roles?.each { role ->
authorities.add(new SimpleGrantedAuthority(role.authority))
}
return authorities
}
}
次にconf/spring/resources.groovy
:
import com.app.users.UserEmailUserService
// Place your Spring DSL code here
beans = {
userDetailsService(UserEmailUserService){
grailsApplication = ref('grailsApplication')
}
}
user.roles
これは、ユーザー クラスで作成したカスタム コールです。私はグループの役割などを持っているので:
Set<Role> getRoles() {
UserRole.findAllByUser(this)*.role
}