You can use the Java Authentication and Authorization Service (JAAS) login framework to
obtain the authentication data from your application.
About this task
Your application can perform a JAAS programmatic login using the
DefaultPrincipalMapping
JAAS context entry name to obtain a Subject object with a
javax.resource.spi.security.PasswordCredential
instance in the private credentials
set that contains the user name and password configured for an authData
element.
Procedure
-
Add the
appSecurity-2.0
and passwordUtilities-1.0
features in
the server.xml file. For example:
<featureManager>
<feature>appSecurity-2.0</feature>
<feature>passwordUtilities-1.0</feature>
</featureManager>
-
Configure an
authData
element in the server.xml file. For
example:
<authData id="myAuthData" user="myUser" password="myPassword"/> <!-- password can also be encoded -->
Encode the password within the configuration. You can get the encoded value by using the securityUtility encode command.
-
Perform a programmatic login with the
DefaultPrincipalMapping
JAAS login
context entry name from your application servlet or enterprise bean, replacing the mapping alias
with the one you need. For example:
HashMap map = new HashMap();
map.put(com.ibm.wsspi.security.auth.callback.Constants.MAPPING_ALIAS, "myAuthData"); // Replace value with your alias.
CallbackHandler callbackHandler = new com.ibm.wsspi.security.auth.callback.WSMappingCallbackHandler(map, null);
LoginContext loginContext = new LoginContext("DefaultPrincipalMapping", callbackHandler);
loginContext.login();
Subject subject = loginContext.getSubject();
Set<javax.resource.spi.security.PasswordCredential> creds = subject.getPrivateCredentials(javax.resource.spi.security.PasswordCredential.class);
PasswordCredential passwordCredential = creds.iterator().next();
Note: The error handling is not shown for simplicity. A
javax.security.auth.login.LoginException
is returned if the authentication alias
requested does not exist or is malformed.
-
Obtain the user name and password from the
PasswordCredential
. For
example:
String userName = passwordCredential.getUserName();
char[] password = passwordCredential.getPassword();
// Do something with the userName and password.
-
If Java 2 Security is enabled, then the application must be granted the
javax.security.auth.PrivateCredentialPermission
. For example, grant the permission
in the application's META-INF/permissions.xml file to access the
PasswordCredential
object:
<?xml version="1.0" encoding="UTF-8"?>
<permissions xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/permissions_7.xsd" version="7">
<permission>
<class-name>javax.security.auth.PrivateCredentialPermission</class-name>
<name>javax.resource.spi.security.PasswordCredential * "*"</name>
<actions>read</actions>
</permission>
<!-- Other permissions -->
</permissions>