Spring Boot 4 and Vaadin 25 - AuthenticationContext not initialized in Service

Hi, I am working on https://codaco.app. In the last weeks I have been migrating the backend to spring boot 4 and vaadin 25 and it works pretty well so far but there is one issue that I can not solve.

I have a service that injects the AuthenticationContext and that I use to e.g. get the logged in user. In spring boot 3.x the context gets injected correctly and I can query login status and the logged in user. In spring boot 4.x it is injected, too, but the user is always anonymousUser and it says, the user is not logged in - even after a validated successful login.

I assume this could be related to the @Service and the UI run in different threads, but I don’t find any information on that. Spring boot 4 introduced virtual threads and I even deactivated the feature setting spring.threads.virtual.enabled to false but without success.

This is my service class. Hope you can give me a hint:

@Service
class SecurityService(
    private var authenticationContext: AuthenticationContext
    ) {

    fun getAuthenticatedUser(): UserDetails? {
        val ac = authenticationContext.getAuthenticatedUser(UserDetails::class.java).getOrNull()
        println("Authenticated user $ac")
        // this prints "Authenticated user null"

        val auth = SecurityContextHolder.getContext().authentication
        println("Spring auth ${auth?.isAuthenticated} as ${auth?.principal}")
        // this prints false and anonymousUser

        val principal = auth?.principal
        println("Principal is ${principal?.javaClass?.kotlin?.simpleName}")
        // this prints string

        if (principal is UserDetails) {
            // I never get here, even if logged it. Worked in vaadin 24 and spring boot 3.x
            return principal
        }
        return null
    }
}

Can you share your WebSecurity configuration? Normally your setup should work

What’s the type of principal?

Hi Christian, hi Simon,

thanks for your replies. I actually found my mistake. My SecurityFilterChain contained a definition for a stateless session policy. This was required because I offer a REST API for a mobile app. Surprisingly, this did work with vaadin 24/spring boot 3 - but apparently not in the current setup.

I split the security configuration into two beans, one for the REST API, one for vaadin. Whereas only the first remained stateless. Now everything works like a charm.

1 Like