如何在 Spring 启动时更新 Principal 对象的数据

How to update data on Principal object on Spring Boot

我正在使用 Spring Boot 和 OAuth2 构建 REST API,我在尝试更新 Principal[= 时遇到了麻烦32=] 会话中的对象。我需要在更新用户时执行此操作,因为数据库中的某些关系可能会发生变化,而且我认为检查数据库中的用户以获取每个请求的值并不是一个好的选择。

我读了很多帖子说解决方案只是将新上下文添加到 SecurityContextHolder,像这样:

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    CustomUserDetails u = (CustomUserDetails)authentication.getPrincipal();
    //Change here some details from user and update the database

    SecurityContextHolder.getContext().setAuthentication(authentication);

但就我而言,它不起作用,如果我使用相同的访问令牌发出请求,Principal 对象总是返回旧值。

--- 编辑 ---

我的安全配置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();
   }
}

还有我的 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();
   }
}

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