Grails springSecurityService.getCurrentUser() 在使用自定义 Authent



我的应用中的一个控制器需要由根据外部数据库进行身份验证的用户访问。

我已经设置了一个自定义用户对象,

class CustomUserDetails extends GrailsUser {
    final String externalId
    CustomUserDetails(String username, String password, boolean enabled,
        boolean accountNonExpired, boolean credentialsNonExpired,
        boolean accountNonLocked,
        Collection<GrantedAuthority> authorities,
        long id, String externalId) {
        super(username, password, enabled, accountNonExpired,
        credentialsNonExpired, accountNonLocked, authorities, id)
        this.externalId = externalId 
    }       
}

和自定义身份验证提供程序

class CustomAuthenticationProvider implements AuthenticationProvider {
    def springSecurityService
    Authentication authenticate(Authentication customAuth) {
    /* Do stuff to validate the user's credentials here */
        def userDetails = new CustomUserDetails(customAuth.getPrincipal(), customAuth.getCredentials(), true, true, true, true, 
                [new GrantedAuthorityImpl('ROLE_SPECIAL_USER')], 9999999, "externalDatabaseIdString")
        def token = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.authorities)
        return token
    }
    boolean supports(Class authentication) {
        return true
    }
}

我在 Config.groovy 中创建了条目以将其添加到 springsecurity.providerNames 列表中,并将以下内容添加到 conf/spring/resources.groovy

beans = {
customAuthenticationProvider(info.proadvisors.auth.CustomAuthenticationProvider){ bean ->   bean.autowire = "byName" }
userDetailsService(org.codehaus.groovy.grails.plugins.springsecurity.GormUserDetailsService){ bean -> bean.autowire = "byName" }
}

这就是问题所在 - 在我的控制器中,正在注入 springSecurityService,但 springSecurityService.getCurrentUser(( 为空,当我尝试访问应该位于经过身份验证的用户对象的 externalId 属性时返回空指针异常。

如果在我的 CustomAuthenticationProvider 中,我没有创建 CustomUserDetails 的实例,而是使用 GormUserDetailsService 给我一个 GrailsUser 对象并使用它来构建令牌,则控制器工作正常,getCurrentUser(( 工作。

关于为什么这不起作用的任何想法?

springSecurityService.getPrincipal(( 给了我我想要的东西。

不知道为什么getCurrentUser((不起作用,而getPrincpal((可以,但它就是这样。

最新更新