Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version
Go to top

Cross Domain/Platform Authentication and Data Transfer

, 29 Dec 2008
Introduces a methodology for authenticating user in cross domain/platform and transferring user data from one site to another during the authentication process.
CrossSiteAuthentication.zip
CrossSiteAuthentication
AuthenticationSite
App_Code
App_Data
CustomerDB.mdf
CustomerDB_Log.LDF
Bin
Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll.refresh
Microsoft.Practices.ObjectBuilder.dll
images
line.JPG
Site1.JPG
Site2.JPG
ThirdPartySite
App_Code
App_WebReferences
AuthenticationService
AuthenticationService.disco
AuthenticationService.discomap
AuthenticationService.wsdl
images
line.JPG
Site1.JPG
Site2.JPG
using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Web;
using System.Collections.Specialized;
using System.Text;

/// <summary>
/// Commonly use code for Cross site authentication
/// </summary>
public static class Authentication
{
    public static DataTable VerifyCredentials(string userName, string password)
    {
        //confirm credentials. upone success, return a single record for this user
        return ExecuteDataSet("Customer_Login", new object[] { userName, password }).Tables[0];
    }

    //this method retrieve a complete set of user data that a third party app needs
    public static DataSet RetrieveUserDataSet(int siteID, string userID)
    {
        //siteID determines storedproc name. 
        DataSet ds = ExecuteDataSet(GetDataTransferProc(siteID), new object[] { userID });
        return ds;
    }

    private static string GetDataTransferProc(int siteID)
    {
        string Proc = "";
        SqlDataReader rd = ExecuteDataReader("SiteInfo_GetSiteInfo", new object[] { siteID });
        if (rd.Read())
            Proc = rd["DataTransferProcName"].ToString();
        if (Proc == "")
            throw new Exception("No data transfer sql stored procedure is specified for this site.");

        return Proc;
    }

    public static SqlDataReader ExecuteDataReader(string storedProc, object[] parameters)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase();
            DbCommand dbcom = db.GetStoredProcCommand(storedProc, parameters);
            return (SqlDataReader)db.ExecuteReader(dbcom);
        }
        catch
        {
            throw;
        }
    }
    public static int ExecuteNonQuery(string storedProc, object[] parameters)
    {
        Database db = DatabaseFactory.CreateDatabase();
        DbCommand dbcom = db.GetStoredProcCommand(storedProc, parameters);
        return db.ExecuteNonQuery(dbcom);
    }

    public static DataSet ExecuteDataSet(string storedProc, object[] parameters)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase();
            DbCommand dbcom = db.GetStoredProcCommand(storedProc, parameters);
            return db.ExecuteDataSet(dbcom);
        }
        catch
        {
            throw;
        }
    }
    //The return url to be used to send user back to partner site needs to be parsed to add the AuthID properly
    public static string WellFormReturnUrl(string originalReturnUrl, string authID)
    {
        string WellFormedUrl = "";
        //check if the original return url has parameters attached already. encryptedParameter has to be UrlEncoded.
        int Position = originalReturnUrl.IndexOf("?");
        if (Position != -1)
        {
            //? exists. original url has some parameters already, append the ecryptedParameter to the end with a "&"
            WellFormedUrl = originalReturnUrl + "&AuthID=" + HttpUtility.UrlEncode(authID);
        }
        else //original url does not have any parameters, append EncryptedData with "?"
        {
            WellFormedUrl = originalReturnUrl + "?AuthID=" + HttpUtility.UrlEncode(authID);
        }
        return WellFormedUrl;
    }
    //Build user data in SqlDataReader into a text string
    public static string SerializeParameters(NameValueCollection userData)
    {
        StringBuilder MyString = new StringBuilder();
        foreach (string k in userData.AllKeys)
        {
            MyString.Append(k);
            MyString.Append('=');
            //for url use, urlencode is required
            MyString.Append(HttpUtility.UrlEncode(userData[k]));//encode chars like '=', &, ' ' etc.
            MyString.Append('&');
        }
        return MyString.ToString();
    }
    //place all user authentication related data into a data collection so that it is easy to handle
    public static NameValueCollection BuildUserDataCollection(DataTable tbl, int minutesToExpire, int siteID, string returnUrl)
    {
        NameValueCollection UserDataCollection = new NameValueCollection();
        DataRow Row = tbl.Rows[0];
        for (int i = 0; i < tbl.Columns.Count; i++)
        {
            //IMPORTANT: in the collection UserID is required.
            UserDataCollection.Add(tbl.Columns[i].ColumnName.ToString(), Row[i].ToString());
        }
        //add expiration
        UserDataCollection.Add("ExpirationDateTime", DateTime.Now.AddMinutes(minutesToExpire).ToString());
        //add siteID
        UserDataCollection.Add("SiteID", siteID.ToString());
        //add returnUrl
        UserDataCollection.Add("ReturnUrl", returnUrl);

        return UserDataCollection;
    }
    public static NameValueCollection DeserializeUserData(string serializedString)
    {
        NameValueCollection UserData = new NameValueCollection();
        string[] NameValuePairs = serializedString.Split('&');
        for (int i = 0; i < NameValuePairs.Length; i++)
        {
            string[] NameValue = NameValuePairs[i].Split('=');

            if (NameValue.Length == 2)
            {
                if (NameValue[0].ToLower() == "expirationdatetime")//replace the default expiration datetime.
                {
                    if (Convert.ToDateTime(HttpUtility.UrlDecode(NameValue[1])) <= DateTime.Now)
                        throw new Exception("The Url has expired.");
                }
                UserData.Add(NameValue[0], HttpUtility.UrlDecode(NameValue[1]));
            }
        }
        return UserData;
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Tomz_KV
Web Developer
United States United States
Web & Database Developer. Design and implement web and database applications utilizing Microsoft and other development tools.

| Advertise | Privacy | Mobile
Web01 | 2.8.140905.1 | Last Updated 29 Dec 2008
Article Copyright 2008 by Tomz_KV
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid