Thursday, October 18, 2012

jquery ajax authentication Example


Ajax calls can be authenticated with a pair of username and password credentials to secure the resources shared by the server, the sever can mandate all the request calls to send a valid set of credentials to process the request.

In this post we shall see on how to make a request to a server by passing the username and password along with the request, additionally we will also encrypt the username and password using base64 encryption.

In perform the base64 encryption we will have to add the
base64.js file. The base64.js file can be obtained from the webtoolkit site.
http://www.webtoolkit.info/javascript-base64.html

The following script makes a request to the server and passes the username and password required to authenticate the request.

var username = Base64.encode("guest");
var password = Base64.encode("guest");
$.ajax({
    url: "AjaxData.aspx?ID=1&username=" + username + "&password=" + password,
    cache: false,
    async: false,
    dataType: "xml",
    success: function(result) {
        $(result).find("Name").each(function() {
            nameList = nameList + $(this).text() + "
"
;
        });
        $("#divAuthenticate").html(nameList);
    }
});


Here is a full Example.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Ajax Properties</title>
    <script type="text/javascript" src="JavaScript/jquery-1.7.2.js"></script>
    <script type="text/javascript" src="JavaScript/base64.js"></script>
    <script
        type="text/javascript"
        language="javascript">
        $(document).ready(function() {
            // Authenticated Ajax Call
            $('#btnAuthenticate').click(function(event) {
                event.preventDefault();
                var nameList = "";
                var username = Base64.encode("guest");
                var password = Base64.encode("guest");
                $.ajax({
                    url: "AjaxData.aspx?ID=1&username=" + username + "&password=" + password,
                    cache: false,
                    async: false,
                    dataType: "xml",
                    success: function(result) {
                        $(result).find("Name").each(function() {
                            nameList = nameList + $(this).text() + "
"
;
                        });
                        $("#divAuthenticate").html(nameList);
                    }
                });
            });
        });
    </script>                 
</head>
<body>
    <form id="AjaxHandlers" runat="server">
        <table border="1">
            <tr>
                <td><b>Action</b></td>
                <td><b>Response</b></td>
            </tr>
            <tr valign="middle">
                <td>
                    <asp:Button
                        ID="btnAuthenticate"
                        runat="server"
                        Text="Authenticate Call" />
                </td>
                <td align="center">
                    <br /><div                           id="divAuthenticate"></div> 
                </td>
            </tr>
        </table>       
    </form>
</body>
</html>

Run the example click on the Authenticate call button, place a breakpoint in the server side code and notice that the credentials are encoded.

Here is the code for the serer side page 
AjaxData.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;

namespace jQuery
{
    public partial class AjaxData : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((Request.Form != null)&&(Request.Form.Count > 0))
            {
                // Process HTTP POST Request
                string strFilterID = Request.Form["ID"].ToString();
                List<clsContacts> lstContacts = getContactByID(strFilterID);
                Response.Write(buildXML(lstContacts));
            }
            else
            {
                // Process HTTP GET Request
                string strFilterID = Request.QueryString["ID"].ToString();
                //
                if (Request.QueryString["username"] != null)
                {
                    string strUserName = base64Decode(Request.QueryString["username"].ToString());
                    string strPassword = base64Decode(Request.QueryString["password"].ToString());
                }
                List<clsContacts> lstContacts = getContactByID(strFilterID);
                Response.Write(buildXML(lstContacts));
            }
        }
        //
        private List<clsContacts> getContactList()
        {
            List<clsContacts> lstContacts = new List<clsContacts>();
            lstContacts.Add(new clsContacts("1","John", "34"));
            lstContacts.Add(new clsContacts("2", "David", "24"));
            return lstContacts;
        }
        //
        private List<clsContacts> getContactByID(string filterKey)
        {
            List<clsContacts> lstContacts = new List<clsContacts>();
            lstContacts.Add(new clsContacts("1", "John", "34"));
            lstContacts.Add(new clsContacts("2", "David", "24"));
            //
            var filteredContacts = from c in lstContacts
                                   where c.ID.Equals(filterKey)
                                    select c;
            //
            return filteredContacts.ToList();
        }
        //
        private string buildXML(List<clsContacts> lstContacts)
        {
            XElement contactsXML = new XElement("Contacts");
            //
            foreach (clsContacts objContact in lstContacts)
            {
                contactsXML.Add(
                    new XElement("Contact",
                        new XElement("Name", objContact.Name),
                        new XElement("Age", objContact.Age)
                    )
                );
            }
            return contactsXML.ToString();
        }
        //
        public string base64Encode(string data)
        {
            try
            {
                byte[] encData_byte = new byte[data.Length];
                encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
                string encodedData = Convert.ToBase64String(encData_byte);
                return encodedData;
            }
            catch (Exception e)
            {
                throw new Exception("Error in base64Encode" + e.Message);
            }
        }
        //
        public string base64Decode(string data)
        {
            try
            {
                System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
                System.Text.Decoder utf8Decode = encoder.GetDecoder();

                byte[] todecode_byte = Convert.FromBase64String(data);
                int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
                char[] decoded_char = new char[charCount];
                utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
                string result = new String(decoded_char);
                return result;
            }
            catch (Exception e)
            {
                throw new Exception("Error in base64Decode" + e.Message);
            }
        }
    }
    //
    //
    public class clsContacts
    {
        public string _id;
        public string _name;
        public string _age;
        //
        public clsContacts(string strID, string strname, string strAge)
        {
            this._id = strID;
            this._name = strname;
            this._age = strAge;
        }
        //
        public string ID
        {
            get { return _id; }
            set { _id = value; }
        }
        //
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        //
        public string Age
        {
            get { return _age; }
            set { _age = value; }
        }
    }

Search Flipkart Products:
Flipkart.com

No comments: