How to read J2C (Java 2 Connector) entries in IBM WebSphere

IBM WebSphere has an easy way to configure security / login data and apply it to any resource, such as JDBC connections, Email providers, etc. You simply goto the IBM Admin console and open the Global Security section. You can add a JAAS – J2C entry and then apply it for resources requiring authentication. Seems like a great way to configure login/password data on your container and avoid hard coding, a config file, or in a database.


I wanted to apply the same concept for custom functionality written in java code then look up a J2C entry for login & password data. For example, I had an outbound REST call that needed a login. However, I couldn’t really find any obvious examples or documentation on how to look up J2C entries.

Here’s what I ended up doing, hopefully it will help save someone some time:

public static getJ2CData(String j2cAlias) throws Exception {
        String methodName = "getJ2CData"; result = null;
        try {
            // ----------WAS 6 change -------------
            HashMap map = new HashMap();
            CallbackHandler cbh = (WSMappingCallbackHandlerFactory.getInstance()).getCallbackHandler(map, null);
            LoginContext lc = new LoginContext("DefaultPrincipalMapping", cbh);
   subject = lc.getSubject();
            java.util.Set creds = subject.getPrivateCredentials();            
            result = ( creds.toArray()[0];
       } catch(Exception e) {
            log.severe("APPLICATION ERROR: cannot load credentials for j2calias = " + j2cAlias);
            throw new Exception("Unable to get credentials");
        return result;

All J2C entries are uniquely identified by an Alias when you create them. You just need to pass in that Alias and the method should return a PasswordCredential object.
The object has UserName and Password fields you can easily retrieve: credentials = getJ2CData("SOME ALIAS");

Note, these values are all encrypted by WebSphere but once you retrieve them they will be in plain text. Security should still be enforced after retrieval.