Grails springSecurityService.currentUser returns null



我有这个服务类:

class UserService {
    def springSecurityService
    @Listener(topic = 'currentUser', namespace = 'auth')
    public User getCurrentUser(){
        return springSecurityService.currentUser
    }
    def authenticate(OAuthToken oAuthToken){
        SecurityContextHolder.context.authentication = oAuthToken
        return springSecurityService.currentUser
    }
}

如果我使用authenticate方法,springSecurityService.currentUser将返回当前用户。但如果我已经登录,我想用getCurrentUser方法获得一个当前用户,它返回null。我调试了Springsecurityservice.getCurrentUser方法,方法"isLoggedIn"返回false。

但如果我尝试一下,在我看来它是有效的:

<sec:ifLoggedIn>Yeeees</sec:ifLoggedIn>

更新:

当我运行UserService.getCurrentUser时,SecurityService中的SCH.context.authentication返回null。在该调用之后,视图被呈现,并且SCH.context.authentication返回一个权限验证。

更新2:

我分析了它,似乎只有当我将它与事件总线一起使用时,它才会发生。若我直接从控制器调用getCurrentUser,它可以正常工作,但若我使用事件总线,它就不能正常工作。我使用平台核心插件中的事件总线。事件总线是否有另一个SCH.conf?

我找到了一个解决方案。问题是事件总线在线程中工作,默认情况下spring上下文不会传递到线程。

配置中的选项"上下文持有者策略"解决了这个问题:

grails.plugin.springsecurity.sch.strategyName = org.springframework.security.core.context.SecurityContextHolder.MODE_INHERITABLETHREADLOCAL

http://grails-plugins.github.io/grails-spring-security-core/latest/#miscProperties

您可以获取主体,然后搜索用户,在我的情况下,域是AppUser

        def user = springSecurityService.getPrincipal()
        def testUser =AppUser.findByUsername(user.username)

最新更新