static final String DELEGATED_USER_KEY = ServerSecurityInterceptor.class.getName() + ".DelegationUser";
@AroundInvoke
public Object aroundInvoke(final InvocationContext invocationContext) throws Exception {
Principal desiredUser = null;
RealmUser connectionUser = null;
Map<String, Object> contextData = invocationContext.getContextData();
if (contextData.containsKey(DELEGATED_USER_KEY)) {
desiredUser = new SimplePrincipal((String) contextData.get(DELEGATED_USER_KEY));
Connection con = RemotingContext.getConnection();
if (con != null) {
UserInfo userInfo = con.getUserInfo();
if (userInfo instanceof SubjectUserInfo) {
SubjectUserInfo sinfo = (SubjectUserInfo) userInfo;
for (Principal current : sinfo.getPrincipals()) {
if (current instanceof RealmUser) {
connectionUser = (RealmUser) current;
break;
}
}
}
} else {
throw new IllegalStateException("Delegation user requested but no user on connection found.");
}
}
SecurityContext cachedSecurityContext = null;
boolean contextSet = false;
try {
if (desiredUser != null && connectionUser != null
&& (desiredUser.getName().equals(connectionUser.getName()) == false)) {
try {
// The final part of this check is to verify that the change does actually indicate a change in user.
// We have been requested to switch user and have successfully identified the user from the connection
// so now we attempt the switch.
cachedSecurityContext = SecurityContextAssociation.getSecurityContext();
final SecurityContext nextContext = SecurityContextFactory.createSecurityContext(desiredUser,
new CurrentUserCredential(connectionUser.getName()), new Subject(), "fooSecurityDomain");
SecurityContextAssociation.setSecurityContext(nextContext);
// keep track that we switched the security context
contextSet = true;
RemotingContext.clear();
} catch (Exception e) {