如何以编程方式更改Spring Security中的当前Principal?

时间:2016-06-08 01:11:50

标签: java spring spring-security spring-security-oauth2

如何更改当前在应用程序中登录的当前用户?

以下是我用来将当前用户切换到另一个帐户/相对帐户的代码。

   User user = userService.getUser(dependentId);

        String access_token = authorizationToken.replace("Bearer","").trim();

        if(SecurityContextHolder.getContext().getAuthentication() != null) {
           User relative = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            for(Role role: relative.getRoles()) {
                if(role.getName().equals("PATIENT")) {
                    OAuth2Authentication oauth2 = defaultTokenServices.loadAuthentication(access_token);

                    User o3 =(User)SecurityContextHolder.getContext()
                            .getAuthentication()
                            .getPrincipal();

                    Authentication authentication = new UsernamePasswordAuthenticationToken(user,
                            user.getPassword()
                            ,user.getAuthorities());

                    OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oauth2.getOAuth2Request(),authentication);

                    SecurityContextHolder.getContext().setAuthentication(oAuth2Authentication);

                    User o5  = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                    break;
                }
            }

我在调试器上运行了代码,我希望o5与o3不同,但它们仍然是相同的

0 个答案:

没有答案