Thursday, February 4, 2016

How to access authentication alias from WebSphere Application Server> J2C

You can use the following code to obtain credentials from J2C authentication data entry:

import com.ibm.wsspi.security.auth.callback.Constants;
import com.ibm.wsspi.security.auth.callback.WSMappingCallbackHandlerFactory;
import javax.resource.spi.security.PasswordCredential;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginContext;

Map map = new HashMap();
map.put(Constants.MAPPING_ALIAS, "YOUR_J2C_DATA_ALIAS");
CallbackHandler callbackHandler = WSMappingCallbackHandlerFactory.getInstance().getCallbackHandler(map, null);

LoginContext loginContext = new LoginContext("DefaultPrincipalMapping", callbackHandler);
loginContext.login();

Subject subject = loginContext.getSubject();
Set credentials = subject.getPrivateCredentials();

PasswordCredential passwordCredential = (PasswordCredential) credentials.iterator().next();

String user = passwordCredential.getUserName();
String password = new String(passwordCredential.getPassword());

Reference link: http://stackoverflow.com/questions/4663534/how-to-access-authentication-alias-from-ejb-deployed-to-websphere-6-1/6355992#6355992

4 comments:

  1. Does this work in Websphere 8.5.5.x? I am facing login context error.
    javax.security.auth.login.LoginException: Login Failure: all modules ignored
    at javax.security.auth.login.LoginContext.invoke(LoginContext.java:933)
    at javax.security.auth.login.LoginContext.access$000(LoginContext.java:215)
    at javax.security.auth.login.LoginContext$4.run(LoginContext.java:706)
    at javax.security.auth.login.LoginContext$4.run(LoginContext.java:704)
    at java.security.AccessController.doPrivileged(AccessController.java:488)
    at javax.security.auth.login.LoginContext.invokePriv(LoginContext.java:703)

    ReplyDelete
    Replies
    1. I had tried on WASv8.0 so it should work. There are some security parameters that you may need to enable. Checkout this IBM Knowledge center link: http://www.ibm.com/support/knowledgecenter/SSEQTP_8.5.5/com.ibm.websphere.wlp.doc/ae/twlp_dev_prog_login_auth_data.html

      Delete
    2. Thanks for the quick reply.. is it recommended to change the values directly in server.xml? if possible share the server.xml and path to change the values..Also is there any way we can change in admin console?

      Delete
    3. It Works Thanks!, we have use Node name in the alias (Node04_j2calias). If not a valid Alias it throws Login Failure: all modules ignored

      Delete