gpt4 book ai didi

grails - 在Spring Security中定制身份验证

转载 作者:行者123 更新时间:2023-12-02 13:56:39 24 4
gpt4 key购买 nike

在我的Grails应用中,我使用的是Spring Security插件,并定义了一个custom 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和/或postAuthenticationChecks bean添加其他检查。从插件中对它们进行子类化并添加您自己的检查,然后将其注册到resources.groovy中,

preAuthenticationChecks(MyPreAuthenticationChecks)
postAuthenticationChecks(MyPostAuthenticationChecks)

关于grails - 在Spring Security中定制身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20751344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com