Using LDAP Login Module to authenticate users with LDAP server in hybrid applications

improve this page | report issue


You can use the LdapLoginModule class to authenticate users with LDAP servers such as OpenLDAP or Active Directory.
The LdapLoginModule class implements the UserNamePasswordLoginModule interface. Therefore, it must be used in conjunction with an authenticator that implements the UsernamePasswordAuthenticator interface. For example: FormBasedAuthenticator.
For more information about how to implement UsernamePasswordAuthenticator interface, see Custom Authenticator and Login Module.

In this tutorial, you learn how to configure and use the LdapLoginModule class to protect various IBM MobileFirst Platform Foundation entities.

Configuring the authenticationConfig.xml file


Add an authentication realm to the realms section of the authenticationConfig.xml file and call it LDAPRealm.
Use FormBasedAuthenticator in the className element because it implements the required UsernamePasswordAuthenticator interface.
This realm uses LDAPLoginModule as a login module, which will be defined later.

<realm loginModule="LDAPLoginModule" name="LDAPRealm">

To protect a specific resource add the onLoginUrl element as follow:

<realm loginModule="LDAPLoginModule" name="LDAPRealm">

Login Module

Add a login module to the loginModules section and call it LDAPLoginModule.

<loginModule name="LDAPLoginModule">
  <parameter name="ldapProviderUrl" value="ldap://" />
  <parameter name="ldapTimeoutMs" value="2000" />
  <parameter name="ldapSecurityAuthentication" value="simple" />
  <parameter name="validationType" value="searchPattern" />
  <parameter name="ldapSecurityPrincipalPattern" value="{username}" />
  <parameter name="ldapSearchFilterPattern" value="(&amp;amp;(objectClass=user)(sAMAccountName={username})(memberof=CN=Sales,OU=Groups,OU=MyCompany,DC=myserver,DC=com))" />
  <parameter name="ldapSearchBase" value="dc=myserver,dc=com" />

Use com.worklight.core.auth.ext.LdapLoginModule in the className element.
The ldapProviderUrl parameter is mandatory. It defines the URL of your LDAP server.
The ldapTimeoutMs parameter is mandatory. It defines the timeout for LDAP server requests (in milliseconds).
The ldapSecurityAuthentication parameter is mandatory. It defines the type of authentication that is required by LDAP server. The usual value is simple, but you might need to contact LDAP administrator for a more appropriate value.
The validationType parameter is mandatory. It defines the type of validation that is performed.
LdapLoginModule supports three types of validation:

  • exists: The login module tries to establish the LDAP binding by using the supplied credentials. The validation of the credentials is considered successful when binding is successfully established.
  • searchPattern: The login module first tries to run the exists validation. After such validation is successful, the login module issues a search query to the LDAP server context according to the ldapSearchFilterPattern and ldapSearchBase parameters. Credential validation is considered successful if a search query returns one or more entries.
  • custom: Use this value to enable a custom validation logic. The login module tries to run the exists validation after such validation is successful, the login module calls the public boolean doCustomValidation(LdapContext ldapCtx, String username) method. You can override this method by creating a custom Java class in your project and extending the com.worklight.core.auth.ext.UserNamePasswordLoginModule class.

For more information about custom LDAP validation types, see the user documentation.

The ldapSecurityPrincipalPattern parameter is mandatory. It defines the pattern in which LDAP security principal is sent to the LDAP server. You can use a {username} placeholder to inject the user name from the authenticator.
The ldapSearchFilterPattern and ldapSearchBase parameters are optional. They apply only to the searchPattern validation type.

Security Test

Add a security test to the securityTests section of the authenticationConfig.xml file.
You use this security test to protect the adapter procedure. Therefore, use the customSecurityTest element.
Remember the security test name as it will be needed later.

<customSecurityTest name="LDAPSecurityTest">
  <test realm="wl_directUpdateRealm" step="1" />
  <test isInternalUserID="true" realm="LDAPRealm" />

Protecting a JavaScript Adapter

Create an adapter and name it DummyAdapter.
Add a getSecretData procedure and protect it with the security test that you created in previously.

<procedure name="getSecretData" securityTest="LDAPSecurityTest"/>

In this module, the getSecretData procedure returns some hardcoded value:

function getSecretData(){
    return {
        secretData: '123456'

Protecting a Java Adapter

Create a Java adapter. Add a getSecretData method and protect it with the realm you created previously. In this module, the getSecretData procedure returns some hardcoded value:

public JSONObject getSecretData(){
	JSONObject result = new JSONObject();
	result.put("secretData", "123456");
	return result;

To set our new realm as the default user identity for the application, in the application descriptor, add this option:


Creating the client-side authentication components

The application consists of two main div elements:
The AppDiv element is used to display the application content.
The AuthDiv element is used for authentication forms.
When authentication is required, the application hides the AppDiv element and shows the AuthDiv element.
When authentication is complete, it does the opposite.

<div id="AppDiv">
  <input type="button" class="appButton" value="Call protected adapter proc" onclick="getSecretData()" />
  <input type="button" class="appButton" value="Logout" onclick="WL.Client.logout('LDAPRealm',{onSuccess: WL.Client.reloadApp})" />
  <p id="resultDiv"></p>

The buttons are used to call the getSecretData procedure and to log out.

<div id="AuthDiv" style="display:none">
  <div id="loginForm">
    <input type="text" id="usernameInputField" placeholder="Enter username" />
    <br /><br />
    <input type="password" placeholder="Enter password" id="passwordInputField" />
    <br/><br />
    <input type="button" class="formButton" id="loginButton" value="Login" />
    <input type="button" class="formButton" id="cancelButton" value="Cancel" />

The AuthDiv is styled as display:none, because it must not be displayed before authentication is requested by server.

Challenge Handler

Use the WL.Client.createChallengeHandler method to create a challenge handler object. Supply a realm name as a parameter.

var LDAPRealmChallengeHandler = WL.Client.createChallengeHandler("LDAPRealm");


The isCustomResponse function of the challenge handler is called each time a response is received from the server. That function is used to detect whether the response contains data that are related to this challenge handler. It must return true or false.
The default login form that is returned from the MobileFirst server contains the j_security_check string. If the challenge handler detects it in the response, it returns true.

LDAPRealmChallengeHandler.isCustomResponse = function(response) {
    if (!response || !response.responseText) {
        return false;
    var idx = response.responseText.indexOf("j_security_check");
    if (idx >= 0){
        return true;
    return false;


If the isCustomResponse method returns true, the framework calls the handleChallenge function. This function is used to perform required actions, such as hide the application screen or show the login screen.
After the client application detects that the server sent a login form, which means that the server is requesting authentication, the application hides the AppDiv, shows the AuthDiv, and cleans up the passwordInputField.

LDAPRealmChallengeHandler.handleChallenge = function(response){

Other methods

In addition to the methods that the developer must implement, the challenge handler contains functionality that the developer might want to use:

  • The submitLoginForm function sends collected credentials to a specific URL. The developer can also specify request parameters, headers, and callbacks.
  • The submitSuccess function notifies the framework that the authentication process completed successfully. The framework then automatically issues the original request that triggered authentication.
  • The submitFailure function notifies the framework that the authentication process completed with failure. The framework then disposes of the original request that triggered the authentication.
  • Note: You must attach each of these functions to its object. For example: myChallengeHandler.submitSuccess()

Login Button

A click on a login button triggers a function that collects the user name and password from the HTML input fields and submits them to the server.
It is possible to set request headers here, and to specify callbacks.
The form-based authenticator uses the hardcoded j_security_check URL component. You cannot have more than one instance of it.

$('#loginButton').bind('click', function () {
    var reqURL = '/j_security_check';
    var options = {};
    options.parameters = {
            j_username : $('#usernameInputField').val(),
            j_password : $('#passwordInputField').val()
    options.headers = {};
    LDAPRealmChallengeHandler.submitLoginForm(reqURL, options, LDAPRealmChallengeHandler.submitLoginFormCallback);

Cancel Button

A click on a cancel button hides the AuthDiv, shows the AppDiv, and notifies the framework that authentication failed.

$('#cancelButton').bind('click', function () {
});<br />


The callback function checks the response for the containing server challenge again. If a challenge is found, the handleChallenge function is called again.
No challenge present in the server response means that authentication completed successfully. In this case, AppDiv is shown, AuthDiv is hidden, and the framework is notified about the authentication success.

LDAPRealmChallengeHandler.submitLoginFormCallback = function(response) {
    var isLoginFormResponse = LDAPRealmChallengeHandler.isCustomResponse(response);
    if (isLoginFormResponse){
    } else {

Sample application

Click to download the Studio project.

Last modified on November 09, 2016