Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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.

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