SecurityContextHolder return wrong user context on concurrent request

Issue

This Content is from Stack Overflow. Question asked by utsav anand

I am experiencing a weird problem, When multiple concurrent requests comes to a controllerSecurityContextHolder.getContext().getAuthentication().getPrincipal()
return different same user object even if the JWT token is different.

So far tried changing session management to .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) and thread strategy is set to SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_THREADLOCAL) still the isssue persists.

Below is the WebSecurityConfig class configured and a custom filter is added which overrides getPreAuthenticatedPrincipal and getPreAuthenticatedPrincipal of AbstractPreAuthenticatedProcessingFilter class.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityBasicConfig {

    @Autowired
    private Http403ForbiddenEntryPoint http403ForbiddenEntryPoint;
    @Bean
    public Http403ForbiddenEntryPoint http403ForbiddenEntryPoint() {
        return new Http403ForbiddenEntryPoint();
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .exceptionHandling()
            .authenticationEntryPoint(http403ForbiddenEntryPoint)
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .addFilterBefore(preAuthFilter(), BasicAuthenticationFilter.class);
        httpSecurity.csrf().disable();
        SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_THREADLOCAL);
    }
}
public class PreAuthFilter extends AbstractPreAuthenticatedProcessingFilter {
    @Override
    protected Object getPreAuthenticatedPrincipal(HttpServletRequest httpServletRequest) {
        String auth = httpServletRequest.getHeader("PRE-AUTH");
        try {
            User user = new ObjectMapper().readValue(auth, User.class);
            return user;
        } catch (Exception e) {
            return new User();
        }
    }

    @Override
    protected Object getPreAuthenticatedCredentials(HttpServletRequest httpServletRequest) {
        String auth = httpServletRequest.getHeader("PRE-AUTH");
        return auth;
    }
}

Please let me know what I am doing wrong here.
Thanks in advance.

Spring boot version : 2.1.6.RELEASE
Architecture: Microservice



Solution

Check the Answers

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?