Grails springSecurityService.currentUser returns null

↘锁芯ラ 提交于 2019-12-11 11:58:35

问题


I have this service class:

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
    }
}

If I use the authenticate method, springSecurityService.currentUser returns the current user. But if I am already logged in I want to get a current user with getCurrentUser method and it returns null. I debugged the Springsecurityservice.getCurrentUser method and the method "isLoggedIn" returns false.

But if I try this in my view it works:

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

UPDATE:

When I run UserService.getCurrentUser the SCH.context.authentication in SecurityService returns null. After that call, the view is being rendered and SCH.context.authentication returns a right authentication.

UPDATE 2:

I analysed it and it seems to happen only if I use it with event bus. If I call getCurrentUser directly from controller, it works fine, but if I use event bus it doesn't. I use Event Bus from platform-core plugin. Is there another SCH.context for Event Bus?


回答1:


I found a solution. The problem was that Event Bus works within a thread and spring context will not be delivered to threads by default.

The option 'context holder strategy' in config solve this:

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

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




回答2:


You can get the principal and then search the user, in mycase the domain is AppUser

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


来源:https://stackoverflow.com/questions/29536994/grails-springsecurityservice-currentuser-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!