問題は、新しいターゲットユーザー情報を含む新しいトークンを作成する必要があることです。この新しいトークンはクライアントに返されなければならないため、将来の要求では新しいターゲットユーザートークンが使用されます。このケースでは、トークンは(JDBCTokenStoreを使用して)サーバー側で永続化されますが、完全なサーバー側のステートレス環境(JWTトークン)でも機能します。
私たちの環境は、角度1.2のクライアントを持つspring-boot/jhipsterアプリケーションです。この新しいトークンはそのローカルストレージにトークンを保存する(我々の場合、角度1.2アプリケーションで)クライアントに返される
@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;
}
(次のリクエストで使用する):
新しいトークンを作成します。次に、アプリケーションをリロードする必要があります(ターゲットユーザーを更新する最も簡単な方法)。
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()
});
}