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.

Jason Borne said...

Nice post and great content.
Avast Customer Support is here to help you out with the whole procedure to Download Avast Antivirus online, We not only fix your Avast Support related issues but will guide with how to get started with your new Avast product once it gets installed successfully. We at Avast Tech Support provides service to protect your PC from potential online threats and external attacks like viruses, Trojans, malwares, spywares and phishing scams. And Avast Refund. Call on our Avast Phone Number

Gmail Customer service is a third party technical support service for Gmail users when they face any technical issue or error in their Gmail account. Our Gmail Customer Support team solves issues like forgot Gmail account password, Gmail configuration or Sync issues, recover deleted emails and many more. Toll Free number (800) 986-9271

How you install or reinstall Office 365 or Office 2016 depends on whether your Office product is part of an Office for home or Office for business plan. If you're not sure what you have, see what office com setup products are included in each plan and then follow the steps for your product. The steps below also apply if you're installing a single, stand-alone Office application such as Access 2016 or Visio 2016. Need Help with office setup Enter Product Key? Call 1-800-000-0000 Toll Free
Norton Tech Support is a third party service provider and not in any way associated with Norton or any of its partner companies. We offer support for Norton products and sell subscription based additional warranty on computer and other peripheral devices. Call our Toll Free number 1 855 966 3855
Other Services
Norton Toll Free , Office-Setup ,

srjwebsolutions said...

We are leading responsive website designing and development company in Noida.
We are offering mobile friendly responsive website designing, website development, e-commerce website, seo service and sem services in Noida.

Responsive Website Designing Company in Noida
Website Designing Company in Noida
SEO Services in Noida
SMO Services in Noida

Vikas Chaudhary said...

Battery Mantra is Authorized exide car battery dealer in Noida and Greater Noida. We are providing our service in Indirapuram, Delhi, Ashok Nagar.

Exide Battery Dealer in Noida
Battery Dealer in Noida
Authorized Battery Dealer in Noida
Car Battery Dealer in Noida
Car Battery Dealer
Exide Battery Dealer

EG MEDI said... is online medical store pharmacy in laxmi nagar Delhi. You can Order prescription/OTC medicines online. Cash on Delivery available. Free Home Delivery

Online Pharmacy in Delhi
Buy Online medicine in Delhi
Online Pharmacy in laxmi nagar
Buy Online medicine in laxmi nagar
Onine Medical Store in Delhi
Online Medical store in laxmi nagar
Online medicine store in delhi
online medicine store in laxmi nagar
Purchase Medicine Online
Online Pharmacy India
Online Medical Store