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.

j2c

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 javax.resource.spi.security.PasswordCredential getJ2CData(String j2cAlias) throws Exception {
        String methodName = "getJ2CData";
        javax.resource.spi.security.PasswordCredential result = null;
        try {
            // ----------WAS 6 change -------------
            HashMap map = new HashMap();
            map.put(com.ibm.wsspi.security.auth.callback.Constants.MAPPING_ALIAS,j2cAlias);
            CallbackHandler cbh = (WSMappingCallbackHandlerFactory.getInstance()).getCallbackHandler(map, null);
            LoginContext lc = new LoginContext("DefaultPrincipalMapping", cbh);
            lc.login();
            javax.security.auth.Subject subject = lc.getSubject();
            java.util.Set creds = subject.getPrivateCredentials();            
            result = (javax.resource.spi.security.PasswordCredential) creds.toArray()[0];
       } catch(Exception e) {
    	   e.printStackTrace();
            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:

	javax.resource.spi.security.PasswordCredential credentials = getJ2CData("SOME ALIAS");
	System.out.println(credentials.getUserName());
	System.out.println(credentials.getPassword());

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.

Advertisements