问题是您需要创建一个包含新目标用户信息的新令牌。这个新令牌必须发送回客户端,因此对于未来的请求,将使用新的目标用户令牌。在我们的例子中,令牌被持久化在服务器端(使用 JDBCTokenStore),但它也可以在完全服务器端的无状态环境(JWT-Token)中工作。
我们的环境是一个带有 Angular 1.2 客户端的 spring-boot/jhipster 应用程序。
创建新令牌:
@Inject
private UserDetailsService userDetailsService;
@Inject
private AuthorizationServerTokenServices tokenService;
@Inject
private ClientDetailsService clientDetailsService;
public OAuth2AccessToken createImpersonationAccessToken(String login) {
UserDetails userDetails = userDetailsService.loadUserByUsername(login);
log.info("Switching current user to {}", login);
Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
List<GrantedAuthority> impersonationAuthorities = new ArrayList<>(authorities);
Authentication source = SecurityContextHolder.getContext().getAuthentication();
// add current user authentication (to switch back from impersonation):
SwitchUserGrantedAuthority switchUserAuthority =
new SwitchUserGrantedAuthority(AuthoritiesConstants.IMPERSONATION, source);
impersonationAuthorities.add(switchUserAuthority);
UserDetails newUserDetails =
org.springframework.security.core.userdetails.User
.withUsername(login)
.authorities(impersonationAuthorities)
.password("justinventedhere")
.build();
Authentication userPasswordAuthentiation =
new UsernamePasswordAuthenticationToken(newUserDetails, null, impersonationAuthorities);
Map<String, String> parameters = new HashMap<>();
ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
OAuth2Request oauthRequest = new OAuth2Request(parameters, client.getClientId(), client.getAuthorities(), true,
client.getScope(), client.getResourceIds(), null, null, null);
OAuth2Authentication authentication = new OAuth2Authentication(oauthRequest, userPasswordAuthentiation);
OAuth2AccessToken createAccessToken = tokenService.createAccessToken(authentication);
return createAccessToken;
}
这个新令牌被返回给客户端(在我们的例子中是一个 Angular 1.2 应用程序),该客户端将令牌存储在其本地存储中(用于下一个请求)。然后应用程序需要重新加载(更新目标用户的最简单方法):
vm.switchToClient = function (client) {
vm.switchingUser = true;
UserService.switchToClient(client, function(response) {
var expiredAt = new Date();
$localStorage.authenticationToken = response;
window.location.href='#/';
window.location.reload()
});
}