在我的Grails应用中,我使用的是Spring Security插件,并定义了一个自定义userDetailsService Spring bean,以便控制如何检索用户和角色数据,例如
class MyUserDetailsService implements GrailsUserDetailsService {
/**
* Some Spring Security classes (e.g. RoleHierarchyVoter) expect at least one role, so
* we give a user with no granted roles this one which gets past that restriction but
* doesn't grant anything.
*/
static final List NO_ROLES = [new GrantedAuthorityImpl(SpringSecurityUtils.NO_ROLE)]
UserDetails loadUserByUsername(String username, boolean loadRoles) {
return loadUserByUsername(username)
}
UserDetails loadUserByUsername(String username) {
User.withTransaction { status ->
User user = User.findByUsername(username)
if (!user) {
throw new UsernameNotFoundException('User not found', username)
}
def authorities = user.authorities.collect {new GrantedAuthorityImpl(it.authority)}
return new CustomUserDetails(
user.username,
user.password,
user.enabled,
!user.accountExpired,
!user.passwordExpired,
!user.accountLocked,
authorities ?: NO_ROLES,
user.id,
user.name)
}
}
}
CustomUserDetails
上面引用的类仅扩展GrailsUser
了一个name
字段:
class CustomUserDetails extends GrailsUser {
private static final long serialVersionUID = 1;
final String name
CustomUserDetails(String username,
String password,
boolean enabled,
boolean accountNonExpired,
boolean credentialsNonExpired,
boolean accountNonLocked,
Collection<GrantedAuthority> authorities,
long id,
String displayName) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities, id)
this.name = displayName
}
}
除了自定义如何检索用户和角色数据外,我还想控制如何对用户进行身份验证。在我的情况下,身份验证过程并不像通常的“检查输入的密码是否与数据库中的密码匹配”那样简单。验证用户身份的实际细节无关紧要,因此,为简单起见,我们假设如果用户name
字段与输入的密码匹配,那么他将被授予封装在中的角色(权限)CustomUserDetails
。
我想插件中的某个地方可以覆盖Spring Bean,以便自定义默认身份验证机制,但是哪一个呢?因为该name
字段仅由定义CustomUserDetails
,所以我将需要访问返回的此类的实例MyUserDetailsService
才能执行自定义身份验证,这可能吗?
我在这里讨论了自定义登录,示例应用程序具有代码:http : //burtbeckwith.com/blog/?p=1090
但是,如果您只想给用户授予与数据库中不同的角色,我将在中执行MyUserDetailsService
。不需要角色在数据库中-Spring Security只需要一堆GrantedAuthorityImpl
实例。在一个应用程序中,我在身份验证期间自动将ROLE_USER授予常规站点用户,以避免浪费数据库空间。
编辑:
如果您使用的是DaoAuthenticationProvider,则可以通过自定义preAuthenticationChecks
and和/或postAuthenticationChecks
bean在身份验证期间添加其他检查。从插件中对它们进行子类化,并添加您自己的检查,然后将其注册到resources.groovy中。
preAuthenticationChecks(MyPreAuthenticationChecks)
postAuthenticationChecks(MyPostAuthenticationChecks)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句