How  to integrate a Joomla site with some ASP.Net pages. User had to login to Joomla, but some pages in the site were built with .Net. The .Net pages had their own SQL Server database, where Joomla used a MySQL database.

The interesting part was how the .Net pages could verify if a Joomla user was logged in. In this post I will share how I did it. Important is that this is a way it will work, but it is not the safest way. It is hackable, because I used a cookie that stored the (encrypted) Joomla user id. So, if you know which cookie you need and are able to decrypt and/or encrypt with the same keys, you’ll be able to fake a logged in user. Note that this was an acceptable risk. The effect of a break in would be small.
As mentioned I used a cookie to store the Joomla user id. It had to be encrypted to provide as much security as possible. With the next Joomla plugin code the cookie is created on the login event. On the logout event the cookie is deleted. This plugin is written for Joomla 1.5, so in newer version you might need to change some bits

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
 
require_once('TripleDES.php'); // See phpseclib: http://phpseclib.sourceforge.net/
 
// Import library dependencies
jimport('joomla.plugin.plugin');
 
class plgUserSystemIntegration extends JPlugin
{
    function plgUserOVSystemIntegration( &$subject, $config )
    {
        parent::__construct( $subject, $config );
    }
    
    function onLoginUser( $credentials, $options )
    {
        $user = &JFactory::getUser();
 
        // Joomla session parameters
        $userId   = $user->get('id');
 
        // Encrypt the userId to store in cookie
        $key = $this->params->get('key'); // these keys are both used in PHP and .Net
        $iv = $this->params->get('iv');
 
        $crypt = new Crypt_TripleDES();
        $crypt->setKey($key);
        $crypt->setIV($iv);
        $value = $crypt->encrypt(strval($userId));
        // Encode string as text
        $value = bin2hex($value);
        
        setcookie("SIJ10", $value); // The cookie name is the identifier. It might be best to make this configurable
        
        return true;
    }  
    
    function onLogoutUser( $credentials, $options )
    {
        // Overwrite cookie
        setcookie("SIJ10", "", time()-3600);
        
        return true;
    }
}

Besides the logout event, some session management needed to be done in case a user didn’t logout. With the next plugin the cookie is deleted if the Joomla session has ended.

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
 
// Import library dependencies
jimport('joomla.plugin.plugin');
 
class plgSystemSystemIntegrationLogout extends JPlugin
{
    function plgSystemOVSystemIntegrationLogout( &$subject, $config )
    {
        parent::__construct( $subject, $config );
    }
 
    function onAfterDispatch()
    {
        $user = &JFactory::getUser();
 
        // If no user is logged in
        if (!$user->get('id'))
        {
            // If cookie value was set
            if(isset($_COOKIE["SIJ10"]))
            {
                // Overwrite cookie
                setcookie("SIJ10", "", time()-3600);
            }
        }
    }
}

Now the .Net part. With the next method(s) the cookie is retrieved and decrypted. The hex2bin is the equivalent of the PHP function, the binary data can’t be put in a cookie. After that the text is decrypted en parsed to an integer. The basic assumption is that as long as that is possible, a user is logged in. What’s more important, in the SQL server database one table included an application level user (used for backend services) that ‘knows’ the Joomla ID. This way the user could be verified against the database, which would make it more secure.

private void Authenticate()
{
    string CookieUserId = "SIJ10";
    if (Request.Cookies[CookieUserId] != null)
    {
        try
        {
            // Decode from hex
            byte[] encodedDataAsBytes = hex2bin(Request.Cookies[CookieUserId].Value); // Change the text to the binary values
 
            // Decrypt
            TripleDES decryptor = TripleDES.Create();
            UTF8Encoding encoding = new UTF8Encoding();
            decryptor.Key = encoding.GetBytes("abcdefgajdhshsgshsjss12"); // It is best to make these keys configurable!
            decryptor.IV = encoding.GetBytes("abcdefgh");
 
            ICryptoTransform decrypt = decryptor.CreateDecryptor();
            byte[] result = decrypt.TransformFinalBlock(encodedDataAsBytes, 0, encodedDataAsBytes.Length); // Decrypt
 
            string returnValue = encoding.GetString(result);
 
            int id = 0;
            if (int.TryParse(returnValue, out id))
                this.UserId = id;
            else
            {
                // Redirect to the login page
                Response.Redirect("~/Login");
            }
 
            // Some session management is needed
            // Check for session timeout
            if (Session["SessionTimeout"] == null)
            {
                // This is the first page request
                Session["SessionTimeout"] = DateTime.Now;
            }
            else
            {
                // This needs to be included in every page (or use a baseclass) or
                // called with every request
                DateTime lastRequest = (DateTime) Session["SessionTimeout"];
 
                if (DateTime.Now.Subtract(lastRequest).Minutes > 20)
                {
                    Response.Redirect("~/Login");
                }
                else
                {
                    // Update the timeout value
                    Session["SessionTimeout"] = DateTime.Now;
                }
            }
        }
        catch (Exception e)
        {
            Response.Redirect("~/Login");
        }
    }
    else
        Response.Redirect("~/Login");
            
}
 
private byte[] hex2bin(string hexdata)
{
    if (hexdata == null)
        throw new ArgumentNullException("hexdata");
    if (hexdata.Length % 2 != 0)
        throw new ArgumentException("hexdata should have even length");
 
    byte[] bytes = new byte[hexdata.Length / 2];
    for (int i = 0; i < hexdata.Length; i += 2)
        bytes[i / 2] = (byte)(HexValue(hexdata[i]) * 0x10
        + HexValue(hexdata[i + 1]));
 
    return bytes;
}

 
private int HexValue(char c)
{
    int ch = (int)c;
    if (ch >= (int)'0' && ch <= (int)'9')
        return ch - (int)'0';
    if (ch >= (int)'a' && ch <= (int)'f')
        return ch - (int)'a' + 10;
    if (ch >= (int)'A' && ch <= (int)'F')
        return ch - (int)'A' + 10;
    throw new ArgumentException("Not a hexadecimal digit.");
}

Best Joomla Hosting Recommendation


ASPHostPortal.com provides our customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. We offers Joomla hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Joomla Hosting, we should be your best choice.