Skip to content

Instantly share code, notes, and snippets.

@pglezen
Created October 20, 2014 16:56
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pglezen/7e2b676292a56746cc72 to your computer and use it in GitHub Desktop.
Save pglezen/7e2b676292a56746cc72 to your computer and use it in GitHub Desktop.
Obtain credential attributes from WSSubject in a WAS container.
import java.util.logging.Logger;
import javax.security.auth.Subject;
import com.ibm.websphere.security.WSSecurityException;
import com.ibm.websphere.security.auth.WSSubject;
import com.ibm.websphere.security.cred.WSCredential;
...
static List<String> getCallerUserGroups() {
log.entering(CLASSNAME, "getCallerUserGroups");
List<String> groups = new LinkedList<String>();
try {
Subject subject = WSSubject.getCallerSubject();
if (subject != null) {
Set<WSCredential> creds = subject.getPublicCredentials(WSCredential.class);
if (creds.size() == 1) { // We expect exactly one.
WSCredential credential = creds.iterator().next();
log.fine(" User ID = " + credential.getSecurityName());
log.finer(" Unique ID = " + credential.getUniqueSecurityName());
log.finer("Realm Unique ID = " + credential.getRealmUniqueSecurityName());
log.finer(" Realm Name = " + credential.getRealmName());
// This API was fixed before generics came to Java. It returns an
// ArrayList, but can be safely assigned to List<String>.
groups = credential.getGroupIds();
if (!groups.isEmpty()) {
log.finer("Group membership:");
for (String groupName : groups) {
log.finer("\t" + groupName);
}
} else {
log.fine("Group membership is empty.");
}
} else if (creds.size() == 0) {
log.info("WSCredential list is empty.");
} else {
log.warning("WSCredential list size = " + creds.size() + ". This should not happen.");
}
} else {
log.warning("getCallerSubject returned null; probably unauthenticated.");
}
} catch (WSSecurityException e) {
log.logp(Level.SEVERE, CLASSNAME, "getCallerUserGroups", "Failed to get user groups.", e);
} catch (GeneralSecurityException e) {
log.logp(Level.SEVERE, CLASSNAME, "getCallerUserGroups", "Failed to get user groups.", e);
}
log.exiting(CLASSNAME, "getCallerUserGroups");
return groups;
}

The code sample below demonstrates how to obtain user and group information for an authenticated user from within WebSphere Application Server. It uses the WAS security API as documented in the Programming API section of the WAS 8.5.5 Knowledge Center (see packages starting with com.ibm.websphere.security.auth and com.ibm.websphere.security.cred.)

For more details on the WAS authentication model, please see Advanced WAS Authentication on IBM developerWorks. Yes, it's old; but most of it still applies.

@una-tapa
Copy link

una-tapa commented Mar 2, 2021

Thank you, Paul!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment