Basic authentication using Ti.Network.HTTPClient

Most enterprise sites or services provide access to content through basic access authentication. Basic authentication is a method for a HTTP user agent to provide a username and password when making a request. It is important to remember that basic authentication base64 encodes your credentials, not encrypts them. For this reason, it is advised that HTTPS is used when creating network connections.

Titanium provides full support for basic authentication using the SDK's Ti.Network functionality. This recipe describes how to use the Ti.Network.HTTPClient proxy to connect to a website using basic authentication headers.

Getting ready

This recipe uses the Ti.BA CommonJS module as an assist to Titanium's native Ti.Network.HTTPClient. This module and other code assets can be downloaded from the source provided by the book. Installing this module in your project is straightforward. Simply copy the Ti.BA.js file into Resources folder of your project as shown in the following screenshot:

Getting ready

How to do it...

Once you have added the Ti.BA.js file to your project, you need to create your application namespace in the app.js file and use require to import the module into your code as the following code snippet demonstrates:

//Create our application namespace
var my = {
  mod : require('Ti.BA')
};

Creating the recipe UI

This recipe uses a simple UI to illustrate how to establish a basic authenticated network connection. The code snippets in this section walkthrough how to construct the basic authentication testing app shown in the following screenshots:

Creating the recipe UI

Now perform the following steps:

  1. First, a Ti.UI.Window is created to attach all UI elements.
    var win = Ti.UI.createWindow({
      backgroundColor: '#fff', title: 'AES Crypto Example', 
      barColor:'#000',layout:'vertical',fullscreen:false
    });
  2. Next the txtUsername Ti.UI.TextField is added to the Ti.UI.Window. The default value is set to test since it is the default for the browserspy.dk test site used to create our mock test connection.
    var txtUsername = Ti.UI.createTextField({
      value:'test',hintText:'Enter username',
      height:45, left:5, right:5,
      borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED
    });
    win.add(txtUsername);
  3. The txtPassword Ti.UI.TextField is then added to the Ti.UI.Window. The default value is set to test since it is the default for the browserspy.dk test site used to create our mock test connection.
    var txtPassword = Ti.UI.createTextField({
      value:'test',hintText:'Enter password',
      passwordMask:true,height:45, left:5, right:5,
      borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED
    });
    win.add(txtPassword);
  4. Next the txtUrl Ti.UI.TextField is added to the Ti.UI.Window. The default value is set to "http://browserspy.dk/password-ok". The value for txtUrl can be updated to any service requiring basic authentication. For demonstration purposes, the recipe uses the browserspy.dk test site.
    var txtUrl = Ti.UI.createTextField({
      value:'http://browserspy.dk/password-ok.php',
      hintText:'Enter Url',
      height:45, left:5, right:5,
      borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED
    });
    win.add(txtUrl);
  5. Finally the btnConnect Ti.UI.Button is added to the Ti.UI.Window. Later in this recipe, the btnConnect control will be used to initialize the authenticated network connection.
    var btnConnect = Ti.UI.createButton({
      title:'Connect', top:25, height:45, left:5, right:5
    });
    win.add(btnConnect);

Creating a service connection

With the sample UI now in place, the next step in the recipe is to perform a secure network connection using basic authentication. The following snippets are used to create a network connection and display the results shown in the following screenshots:

Creating a service connection

A basic authenticated test network connection is performed when the click event for the btnConnect control is fired as shown in the following code snippet:

btnConnect.addEventListener('click',function(x){
  1. First, the Ti.Network.online property is checked to ensure the device has a network connection. If no network connection is available, the user is alerted and the function is exit.
      if(!Ti.Network.online){
        alert('Network connection is required'),
        return;
      }
  2. Next the onDone function is created. This function is used as a callback for the results of the authentication network connection.
      function onDone(d){
  3. When in the onDone function, the first action performed is to check the results provided in the d.success property. If this property is true, the network connection was successfully completed. Otherwise, the d.error message is printed to the console and the user is notified.
        if(d.success){
          Ti.API.info('Results = ' + 
          JSON.stringify(d.results));
          alert('Authenticated successfully'),
        }else{
          Ti.API.info('error = ' + JSON.stringify(d.error));
          alert('Authenticated Failed'),
        }
      };
  4. The credentials object is then created. This contains the username and password to be used when creating our authenticated connection. Please note these values should be in plain text as demonstrated in taking the values directly from the Ti.UI.TextField controls on the screen.
      var credentials = {
        username:txtUsername.value,
        password:txtPassword.value
      };
  5. The Ti.BA module allows you to configure all of the Ti.Network.HTTPClient options along with controlling and specifying the service's output format. The following snippet demonstrates how to configure the request to set the timeout to 9 seconds, and specify the responseText be the returned response.
      var options = {format:'text', timeout:9000};
  6. Finally a new instance of the Ti.BA module is created and the following are provided:
    • Method: The GET or POST action is performed. In the case of this sample, the POST method is provided.
    • URL: The URL the module uses to connect.
    • Credentials: The credentials object contains the username and password that will be used to create the basic authenticated connection.
    • Callback: This parameter requires a callback method to be provided. In this sample, the onDone method is provided to the module and will return the connection response.
    • Options: These are the configuration options for the Ti.Network.HTTPClient and result type to be returned. If none is provided, the module's default values are returned.
        var basicAuth = new 
        my.mod('POST',txtUrl.value,credentials, onDone,options);
      });
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.184.142