首页 > 解决方案 > How to update data on Principal object on Spring Boot

问题描述

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();
   }
}

标签: spring-bootspring-security-oauth2

解决方案


好的,所以最后我决定正如@r4phG 所说,使当前令牌过期并使用刷新令牌来获取新令牌,从而强制检索更新的用户。


推荐阅读