I'm building a REST API with Spring Boot and OAuth2 and I'm facing with troubles when trying to update the Principal object on a session. I need to do this when updating the user because some relations on the database could change and I think it's not a good option checking the user on the database for getting the values on each request.
I read a lot of posts telling that solution is only adding the new context to a SecurityContextHolder, like this:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
CustomUserDetails u = (CustomUserDetails)authentication.getPrincipal();
//Change here some details from user and update the database
SecurityContextHolder.getContext().setAuthentication(authentication);
But in my case, it doesn't work, if I make a request with the same access token, the Principal object is returning always the old values.
--- EDIT ---
My security config class:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService);
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
And my CustomUserDetailService class:
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Resource
public MyUserRepository usersRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<AppUser> usersOptional = usersRepository.findByEmail(username);
usersOptional.
orElseThrow(() -> new UsernameNotFoundException(username));
return usersOptional
.map(CustomUserDetails::new)
.get();
}
}