How to enable form based authentication in worklight application

  1. The first step is to change the application-descriptor.xml file like this
    <?xml version="1.0" encoding="UTF-8"?>
    <!-- Attribute "id" must be identical to application folder name -->
    <application id="HelloWorklightAuthentication" platformVersion="5.0"
        <name>application's author</name>
        <email>application author's e-mail</email>
        <copyright>Copyright My Company</copyright>
      <usage requireAuthentication="onStartup">
        <realm name="SampleAppRealm"/>
    I made one change in the application-descriptor.xml which is to add usage element with value of requireAuthentication equal to onStartup which means user will have to authenticate at the start of the application. The second change is to add realm element with value equal to SampleAppRealm
  2. The SampleAppRealm is defined in the authenticationConfig.xml file like this
    <?xml version="1.0" encoding="UTF-8"?>
    <tns:loginConfiguration xmlns:tns="" 
        <realm name="SampleAppRealm" loginModule="StrongDummy">
        <realm name="WorklightConsole" loginModule="requireLogin">
        <loginModule name="StrongDummy" canBeResourceLogin="true" isIdentityAssociationKey="false">
        <loginModule name="requireLogin" canBeResourceLogin="true" isIdentityAssociationKey="true">
    The SampleAppRealm is configured to use FormBasedAuthentication, which means we will have to submit a form to j_security_check URL and we will have to use j_username and j_password field name for user name and password on the form The SampleAppRealm uses StrongDummy as loginModule which uses com.worklight.core.auth.ext.NonValidatingLoginModule class for authenticating user name and password. the NonValidatingLoginModule class makes setup easy by not actually validating user name and password, which means no matter what user name and password you pass to it it will always say user logged in.
  3. Change the main .html file for the worklight application so that it looks like this, the basic idea is you should have one div for displaying login form and another for displaying regular application body. We will use JavaScript to check if user is already logged in, if no display login form to the user if no display normal application body.
    <!DOCTYPE html>    
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, 
     maximum-scale=1.0, minimum-scale=1.0, user-scalable=0" />
        <link rel="shortcut icon" href="images/favicon.png" />
        <link rel="apple-touch-icon" href="images/apple-touch-icon.png" />
        <link rel="stylesheet" href="css/reset.css" />
        <link rel="stylesheet" href="css/HelloWorklightApp.css" />
      <body onload="WL.Client.init({showLogger:true})" id="content" style="display: none">
        <div id="AppBody">
          <h1>Your logged in </h1>
          <input type="button" value="Logout" 
       onclick="WL.Client.logout('SampleAppRealm', {onSuccess:  WL.Client.reloadApp});" />
        <div id="AuthBody">
          <div id="loginForm">
            <input type="text" id="usernameInputField" 
      autocorrect="off" autocapitalize="off" /><br />
            <input type="password" id="passwordInputField" autocorrect="off" 
            <input type="button" id="loginButton" value="Login" />
       <script src="js/HelloWorklightApp.js"></script>
        <script src="js/messages.js"></script>
        <script src="js/auth.js"></script>
    The AppBody div displays the normal application body and the AuthBody displays the login form
    Last part is to change the auth.js file so that it looks like this
    var Authenticator = function () {
        var LOGIN_PAGE_SECURITY_INDICATOR = 'j_security_check';
        var USERNAME_INPUT_ID = '#usernameInputField';
        var PASSWORD_INPUT_ID = '#passwordInputField';
        var LOGIN_BUTTON_ID   = '#loginButton';  
        var onSubmitCallback  = null;
        function onFormSubmit() {
          console.log("Entering auth.js.onFormSubmit()");
            var reqURL = './' + LOGIN_PAGE_SECURITY_INDICATOR;
            var params = {
                j_username : $(USERNAME_INPUT_ID).val(),
                j_password : $(PASSWORD_INPUT_ID).val()
            onSubmitCallback(reqURL, {parameters:params});
        return {
            init : function () {
              console.log("Entering auth.js.init()");
                $(LOGIN_BUTTON_ID).bind('click', onFormSubmit);
            isLoginFormResponse : function (response) {
              console.log("Entering auth.js.isLoginFormResponse () " + response);
                if (!response || response.responseText === null) {
                  console.log("Entering auth.js.isLoginFormResponse (), return false");
                    return false;
                var indicatorIdx =;
              console.log("Entering auth.js.isLoginFormResponse (), return " + (indicatorIdx >= 0));
                return (indicatorIdx >= 0);
            onBeforeLogin : function (response, username, onSubmit, onCancel) {
              console.log("Entering auth.js.onBeforeLogin()");
                onSubmitCallback = onSubmit;
                onCancelCallback = onCancel;            
                if (typeof(username) != 'undefined' && username != null){
                else {
          onShowLogin: function() {
            console.log("Entering auth.js.onShowLogin()");
          onHideLogin: function(){        
            console.log("Entering auth.js.onHideLogin()");
    The isLoginFormResponse() is the main method for the authentication framework, it gets called on each response to check if the user is authenticated. Inside this method check the response text to figure out if the user is already authenticated or not. The onShowLogin() page method gets called if the user is not logged in, in that method hide the application body and hide the login form. The onHideLogin() method gets called if the user is already logged in in that case hide the login form and display the body. The onFormSubmit() gets called when user enter the user id and password and clicks submit, that method takes care of submitting the form using AJAX, worklight application is single page application so we cannot actually submit the form normally(I mean without ajax using browser's default form submit functionality)
Once the application is deployed when you access it for the first time you get login page like this
But once you enter user id and password and click submit you should get the application page like this


Shiv said...

wat if der is no auth.js file generated after the project creation??? wat shud i do den??

Christopher Wilson said...

This should work in Worklight v5.0.6.1, please make sure you are using that version.
Otherwise, a way around it is to NOT place the security test on the android environment, and intsead call WL.Client.login(..) in your wlEnvInit or wlCommonInit function. If you have been interested just see it here.