【问题标题】:Grails spring security userDetailService import serviceGrails spring security userDetailService 导入服务
【发布时间】:2019-02-25 05:30:31
【问题描述】:

您好,是否可以将服务导入 customUserDetailService?我有错误

org.springframework.security.authentication.InternalAuthenticationServiceException: 无法在空对象上调用方法 validatePin()

class CustomUserDetailsService implements GrailsUserDetailsService {

def apiService

/**
 * 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 SimpleGrantedAuthority(SpringSecurityUtils.NO_ROLE)]

UserDetails loadUserByUsername(String username, boolean loadRoles)
        throws UsernameNotFoundException {
    return loadUserByUsername(username)
}

@Transactional(readOnly=true, noRollbackFor=[IllegalArgumentException, UsernameNotFoundException])
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    GrailsWebRequest webUtils = WebUtils.retrieveGrailsWebRequest()
    def request = webUtils.getCurrentRequest()
    def countryCode = request.getParameter('country_code')
    def pin = request.getParameter('password')

    def apiUser = apiService.validatePin(countryCode, username, pin)
    println("\n\napiUser: ${apiUser}")

    User user = User.findByUsername(username)
    if (!user) throw new NoStackUsernameNotFoundException()

    def roles = user.authorities


    // or if you are using role groups:
    // def roles = user.authorities.collect { it.authorities }.flatten().unique()

    def authorities = roles.collect {
        new SimpleGrantedAuthority(it.authority)
    }

    return new CustomUserDetails(user.username, user.password, user.enabled,
            !user.accountExpired, !user.passwordExpired,
            !user.accountLocked, authorities ?: NO_ROLES, user.id,
            user.firstName + " " + user.lastName)
}
}

【问题讨论】:

    标签: grails grails-plugin


    【解决方案1】:

    大概您正在resources.groovy 中注册您的自定义用户详细信息服务。在您的 bean 定义中,启用自动装配并添加对您尝试注入的服务的引用。

    userDetailsService(CustomUserDetailsService) {
        it.autowire = true
        apiService = ref('apiService')
    }
    

    【讨论】:

    • 谢谢!想解释一下这个自动连线是如何工作的吗?因为我缺少这个自动接线,所以一切似乎都崩溃了
    • 如果你使用it.autowire = 'byName'而不是it.autowire = true,那么你可以消除apiService = ref('apiService')
    • 如果您在grails-app/services/... 下定义CustomUserDetailsService,那么您可以完全消除resources.groovy 中的bean 定义。
    • @JeffScottBrown 在这种情况下,bean 覆盖了 Spring Security 插件的 bean,因此需要明确定义,否则是的。
    • @doelleri 这对我来说很有意义。
    猜你喜欢
    • 2015-12-28
    • 2013-10-18
    • 2015-12-10
    • 2022-01-14
    • 2014-01-08
    • 2013-01-17
    • 2016-01-06
    • 1970-01-01
    • 2017-11-06
    相关资源
    最近更新 更多