Re: Logging on to customer portal with Windows Authentication

  •  02-22-2008, 10:01 AM

    • Mark is not online. Last active: 07-24-2008, 12:56 PM Mark
    • Top 500 Contributor
      Male
    • Joined on 11-02-2007
    • Raleigh, NC
    • Posts 7
    • Points 161

    Re: Logging on to customer portal with Windows Authentication

    You can indeed use the External Authentication settings to authenticate against active directory.  It took us a bit of effort to get things working.

    This seems like a popular feature request.  Hopefully Axosoft will make this a supported feature in the near future.

    Following is the code we got working.   

    See the administrators guide for information on the settings that must be changed to make external authentication work. (You must make sure the GUID matches what is in the following code)

    You will have to put in your domain settings in the 'ActiveDirectoryAuthentication' method.  This sits in a single aspx page in the root folder of the customer portal.

     Smile  Cheers

     

    <%@ Page Language="C#" Debug="true"  %>
    <%@ Import Namespace="System.Web" %>
    <%@ Assembly Name="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>
    <%@ Import Namespace="System.DirectoryServices" %>
    <%@ Import Namespace="System.Runtime.InteropServices" %>
    <%@ Import Namespace="Axosoft.CustomerPortal.Security" %>

    <script runat="server">
       
        class UserInfo
        {
            public string Company;
            public string FirstName;
            public string LastName;
            public string Email;
            public string ErrorMessage;
            public int ErrorCode;
            public bool Authenticated;

            public UserInfo()
            {
                Company = string.Empty;
                FirstName = string.Empty;
                LastName = string.Empty;
                Email = string.Empty;
                ErrorMessage = string.Empty;
                Authenticated = false;
            }
        }

        private void Page_Load(object sender, System.EventArgs e)
        {
            if (Request.QueryString["Register"] == "1" || Request.QueryString["ForgotPassword"] == "1")
            {
                return;
            }
           
            string UserID = Request.Form["PortalEmail"];
            string Password = Request.Form["PortalPassword"];
            string returnUrl = Request.QueryString["ReturnURL"];

            if (string.IsNullOrEmpty(returnUrl))
            {
                returnUrl = "Default.aspx";
            }
           
            if (Request.QueryString["Logout"] == "1")
            {
                ExpireOntimeCookie();
                Response.Redirect(returnUrl);
                return;
            }


            //we aren't logging out so we log them in.
            if (string.IsNullOrEmpty(UserID) || string.IsNullOrEmpty(Password))
            {
                if (returnUrl.Contains("?"))
                {
                    returnUrl += "&InvalidLogin=1";
                }
                else
                {
                    returnUrl += "?InvalidLogin=1";
                }
                Response.Redirect(returnUrl);
            }

            bool success = Authenticate(UserID, Password);

            if (!success)
            {
                if (returnUrl.Contains("?"))
                {
                    returnUrl += "&InvalidLogin=1";
                }
                else
                {
                    returnUrl += "?InvalidLogin=1";
                }
            }
            Response.Redirect(returnUrl);
        }

        private void ExpireOntimeCookie()
        {
            HttpCookie portalCookie = Request.Cookies["PortalUser"];
            if (portalCookie != null)
            {
                //update the expiration on the portal cookie so that customer portal will correctly detect a logged out user
                Axosoft.CustomerPortal.Security.SecurityProvider customerPortalSecurity = new SecurityProvider();
                portalCookie.Expires = DateTime.Now.AddMinutes(-10);
                portalCookie["Expires"] = HttpUtility.UrlEncode(customerPortalSecurity.EncryptString(portalCookie.Expires.ToString("s")));
                Response.Cookies.Set(portalCookie);
                //Response.Write("Cookie Set<br />");
                //Response.Write(portalCookie.Expires.ToString());
            }
        }

        private bool Authenticate(string UserId, string Password)
        {
            bool success = false;
            UserInfo userData = ActiveDirectoryAuthentication(UserId, Password);

            if (userData.Authenticated)
            {
                CreateOntimeCookie(userData);
                success = true;
            }
            return success;
        }

        private void CreateOntimeCookie(UserInfo user)
        {
            HttpCookie portalCookie = new HttpCookie("PortalUser");
            SecurityProvider customerPortalSecurity = new SecurityProvider();

            portalCookie["PortalEmail"] = HttpUtility.UrlEncode(customerPortalSecurity.EncryptString(user.Email));
            portalCookie["PortalFirstName"] = HttpUtility.UrlEncode(customerPortalSecurity.EncryptString(user.FirstName));
            portalCookie["PortalLastName"] = HttpUtility.UrlEncode(customerPortalSecurity.EncryptString(user.LastName));
            portalCookie["PortalCompany"] = HttpUtility.UrlEncode(customerPortalSecurity.EncryptString(user.Company));

            portalCookie["guid"] = HttpUtility.UrlEncode(customerPortalSecurity.EncryptString("C0DF8003-CC61-4c51-9A0F-EA21631C7199"));
            portalCookie.Expires = DateTime.Now.AddMinutes(this.Session.Timeout);
            portalCookie["Expires"] = HttpUtility.UrlEncode(customerPortalSecurity.EncryptString(portalCookie.Expires.ToString("s")));
            portalCookie.Domain = "ontime.office.abanes.org";
            portalCookie.Path = "/";

            Response.Cookies.Set(portalCookie);
            Response.Write("logged in");
        }

        private UserInfo ActiveDirectoryAuthentication(string UserId, string Password)
        {
            string Domain = "YOURDOMAINHERE";
            string Account = Domain + "\\" + UserId;
            DirectoryEntry searchRoot = new DirectoryEntry("LDAP://DC=host,DC=name,DC=com", Account, Password, AuthenticationTypes.ReadonlyServer);

            UserInfo userInfo = new UserInfo();
            userInfo.Company = Domain;

            //find the users information in Active Directory       
            DirectorySearcher searcher = null;
            try
            {
                string filter = "(&(objectClass=user)(sAMAccountName=" + UserId + "))";
                string[] propertiesToLoad = new string[] { "givenName", "sn", "mail" };
                searcher = new DirectorySearcher(searchRoot, filter, propertiesToLoad);

                SearchResult result = searcher.FindOne();  //because of late binding this is where the real AD authentication happens
                if (result != null)
                {
                    ResultPropertyCollection properties = result.Properties;
                    userInfo.FirstName = properties["givenName"][0].ToString();
                    userInfo.LastName = properties["sn"][0].ToString();
                    userInfo.Email = properties["mail"][0].ToString();
                    userInfo.Authenticated = true;
                }
            }
            catch (COMException exp)
            {
                userInfo.ErrorMessage = exp.Message;
                userInfo.ErrorCode = exp.ErrorCode;
            }
            finally
            {
                if (searcher != null)
                {
                    searcher.Dispose();
                }
                if (searchRoot != null)
                {
                    searchRoot.Dispose();
                }
            }
            return userInfo;
        }
    </script>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head><title>Ontime for The ABA</title></head>
    <body>
    <div>
        This site is configured to authenticate against the domain. So there is not need to register<br />
        <br />
        Do not use your email address to log in.  Instead use your domain user id and password.  The same id and password you use to log in to your computer.
        <br />
        <br />
        <form method="get" action="Default.aspx">
        <input type="submit" id="home" name="home" value="home&gt;&gt;" />
        </form>
    </div>
    </body>
    </html>

     

    Filed under: , ,
View Complete Thread

© 2002 - 2007, Axosoft, LLC. All Rights Reserved. | Privacy
Bug Tracking | Defect Tracking Videos | Help Desk Software