'Spring Boot session scoped bean not reused in RestController across requests

In my application I have to do an expensive initialization of a bean that is dependent on the logged in user. I would like to create the bean once a new session is created and reuse it across all requests within the session.

The problem is that the bean is recreated on every request (which is exactly what I wanted to avoid). It seems that Spring is not able to determine the session and creates a new one on every request.

I am using Spring Security to do the authentication and authorization of the requests. My assumption was that Spring is able to determine a formally created session by the credentials used for the request but maybe this is wrong.

Here are the relevant code snippets:

The session-scoped bean within a @Configuration class

@Bean
@SessionScope
public SessionScopedBean sessionScopedBean() {
    String username = SecurityContextHolder
            .getContext()
            .getAuthentication()
            .getName();
    return doTheExpensiveInitializationOfSessionScopedBean(username);
}

I want this bean to be reused per session. However Spring is calling this method on every request.

Usage of SessionScopedBean in @RestController

@RestController
@RequestMapping("/items")
@Transactional
public class ItemService {

    @Resource(name = "sessionScopedBean")
    SessionScopedBean sessionScopedBean;

    @GetMapping
    @PreAuthorize("hasRole('ROLE_USER')")
    public Items getAllItems() {
        return sessionScopedBean.getAllItems()
    }
}

WebSecurityConfiguration

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().authorizeRequests()
            .anyRequest().permitAll()
            .and()
            .formLogin().loginProcessingUrl("/login")
            .and()
            .addFilterBefore(new CORSFilter(), JWTAuthenticationFilter.class)
            .addFilter(new JWTAuthenticationFilter(authenticationManager(), jwtSecret))
            .addFilter(new JWTAuthorizationFilter(authenticationManager(), jwtSecret))
            // this disables session creation on Spring Security
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);
}

Why is the sessionScopedBean recreated on every request to /items even though the same authentication token is reused? How does Spring determine sessions in RestControllers anyways?

Thanks for any advice!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source