CyberAleks
CyberAleks

Reputation: 1603

Grails springSecurityService.currentUser returns null

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?

Upvotes: 2

Views: 2527

Answers (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)

Upvotes: 0

CyberAleks
CyberAleks

Reputation: 1603

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

Upvotes: 5

Related Questions