protected override void OnLoad(EventArgs e)
        {
            //LogToEventLog("Logoff.OnLoad()", "enter");
            base.OnLoad(e);
            try
            {
                LogToEventLog("DNN.Authentication.SAML.Logoff.OnLoad(post)", string.Format("(Request.HttpMethod: {0}, Session[sessionIndexFromSAMLResponse]: {1}", Request.HttpMethod, Session["sessionIndexFromSAMLResponse"]));

                config = DNNAuthenticationSAMLAuthenticationConfig.GetConfig(PortalId);
                UserInfo user = UserController.GetCurrentUserInfo();
                LogToEventLog("Logoff.OnLoad()", string.Format("Logging off from saml {0}", user == null ? "null" : user.Username));
                X509Certificate2 cert = StaticHelper.GetCert(config.OurCertFriendlyName);


                XmlDocument request = GenerateSAMLLogoffRequest(user.Username);
                request = StaticHelper.SignSAMLRequest2(request, cert);
                string convertedRequestXML = StaticHelper.Base64CompressUrlEncode(request.OuterXml);
                string convertedSigAlg     = HttpUtility.UrlEncode("http://www.w3.org/2000/09/xmldsig#rsa-sha1");
                byte[] signature           = StaticHelper.SignString2(string.Format("SAMLRequest={0}&RelayState={1}&SigAlg={2}", convertedRequestXML, "NA", convertedSigAlg), cert);
                string convertedSignature  = HttpUtility.UrlEncode(Convert.ToBase64String(signature));
                string redirectTo          = config.IdPLogoutURL +
                                             "?SAMLRequest=" + convertedRequestXML +
                                             "&RelayState=NA" +
                                             "&SigAlg=" + convertedSigAlg +
                                             "&Signature=" + convertedSignature
                ;

                base.OnLogOff(e);
                Session.Remove("sessionIndexFromSAMLResponse");

                LogToEventLog("Logoff()", string.Format("Redirecting to {0}", redirectTo));
                Response.Redirect(Page.ResolveUrl(redirectTo), false);
            }
            catch (System.Threading.ThreadAbortException tae)
            {
                LogToEventLog("DNN.Authentication.SAML.Logoff.OnLoad(tae)", "ThreadAbortException");
                //Response.Redirect(Page.ResolveUrl(redirectTo), false);
            }
            catch (Exception ex)
            {
                LogToEventLog("DNN.Authentication.SAML.Logoff.OnLoad()", string.Format("Exception  {0}", ex.Message));
            }
        }
Exemple #2
0
 public ResponseHandler(string rawResponse, X509Certificate2 myCert, string theirCertString) : this(rawResponse, myCert)
 {
     this.theirCert = new X509Certificate2();
     theirCert.Import(StaticHelper.StringToByteArray(theirCertString));
 }
        protected override void OnLoad(EventArgs e)
        {
            if (Request.QueryString["noSAML"] != null)
            {
            }
            else
            {
                base.OnLoad(e);
                staticPortalSettings = PortalSettings;
                string redirectTo = "~/";
                try
                {
                    config = DNNAuthenticationSAMLAuthenticationConfig.GetConfig(PortalId);
                    if (Request.HttpMethod == "POST" && !Request.IsAuthenticated)
                    {
                        //specify the certificate that your SAML provider has given to you
                        string samlCertificate = config.TheirCert;

                        Saml.Response samlResponse = new Saml.Response(samlCertificate);
                        LogToEventLog("Request:", Request.Form["SAMLResponse"].ToString());
                        samlResponse.LoadXmlFromBase64(Request.Form["SAMLResponse"]); //SAML providers usually POST the data into this var
                                                                                      //String xmlExample = "";
                                                                                      //samlResponse.LoadXml(xmlExample);

                        LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("samlResponse is:  ", samlResponse.ToString()));

                        if (samlResponse.IsValid())
                        {
                            LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "saml valid");
                            LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("samlResponse is:  {0}", samlResponse.Xml.ToString()));
                            //WOOHOO!!! user is logged in
                            //YAY!

                            //Obtain optional items
                            string username = "", email = "", firstname = "", lastname = "", displayname = "";
                            var    rolesList         = new List <string>();
                            var    requiredRolesList = new List <string>();
                            try
                            {
                                username = samlResponse.GetNameID();

                                if (username == null)
                                {
                                    LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "USER IS NULL");
                                }
                                else
                                {
                                    if (username == "")
                                    {
                                        LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "USER IS EMPTY");
                                    }
                                }


                                LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("Username is: {0} ", username));

                                email = samlResponse.GetUserProperty(config.usrEmail);
                                if (email == null)
                                {
                                    email = samlResponse.GetUserProperty("email");
                                }
                                firstname = samlResponse.GetUserProperty(config.usrFirstName);
                                if (firstname == null)
                                {
                                    firstname = samlResponse.GetUserProperty("firstName");
                                }
                                lastname = samlResponse.GetUserProperty(config.usrLastName);
                                if (lastname == null)
                                {
                                    lastname = samlResponse.GetUserProperty("lastName");
                                }
                                displayname = samlResponse.GetUserProperty(config.usrDisplayName);
                                if (displayname == null)
                                {
                                    displayname = samlResponse.GetUserProperty("displayName");
                                }

                                var roles = samlResponse.GetUserProperty(config.RoleAttribute);
                                if (!string.IsNullOrWhiteSpace(roles))
                                {
                                    rolesList = roles.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                                }

                                var requiredRoles = samlResponse.GetUserProperty(config.RequiredRoles);
                                if (!string.IsNullOrWhiteSpace(requiredRoles))
                                {
                                    requiredRolesList = requiredRoles.Split(new[] { ',' },
                                                                            StringSplitOptions.RemoveEmptyEntries).ToList();
                                }
                            }
                            catch (Exception ex)
                            {
                                //insert error handling code
                                //no, really, please do
                                LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("Exception:......{0}", ex.InnerException.Message));
                            }


                            UserInfo userInfo = UserController.GetUserByName(PortalSettings.PortalId, username);


                            if (userInfo == null)
                            {
                                //user does not exists, it needs to be created.
                                userInfo = new UserInfo();
                                try
                                {
                                    if (username != null && email != null && firstname != null && lastname != null)
                                    {
                                        if (displayname == null)
                                        {
                                            userInfo.DisplayName = firstname + " " + lastname;
                                        }
                                        else
                                        {
                                            userInfo.DisplayName = displayname;
                                        }

                                        userInfo.FirstName           = firstname;
                                        userInfo.LastName            = lastname;
                                        userInfo.Username            = username;
                                        userInfo.Email               = email;
                                        userInfo.PortalID            = PortalSettings.PortalId;
                                        userInfo.IsSuperUser         = false;
                                        userInfo.Membership.Password = UserController.GeneratePassword();

                                        var usrCreateStatus = new UserCreateStatus();

                                        usrCreateStatus = UserController.CreateUser(ref userInfo);

                                        if (usrCreateStatus == UserCreateStatus.Success)
                                        {
                                            UserInfo usrInfo = UserController.GetUserByName(PortalSettings.PortalId, username);
                                            SetProfileProperties(samlResponse, usrInfo);

                                            //Add roles if needed, since a new user no need to remove roles or process that condition
                                            if (rolesList.Any())
                                            {
                                                AssignRolesFromList(usrInfo, rolesList);
                                            }
                                        }
                                        else
                                        {
                                            LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "Error creating new user..." + usrCreateStatus.ToString());
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "Error creating new user...exception:  " + ex.InnerException.Message);
                                }
                            }
                            else
                            {
                                //User already exists

                                //Wen unlock it if necessary
                                if (userInfo.Membership.LockedOut)
                                {
                                    UserController.UnLockUser(userInfo);
                                }
                                LogToEventLog("DNN.Authentication.SAML.OnLoad(post !auth)", String.Format("FoundUser userInfo.Username: {0}", userInfo.Username));


                                try
                                {
                                    //We update the user's info
                                    userInfo.DisplayName = displayname;
                                    userInfo.FirstName   = firstname;
                                    userInfo.LastName    = lastname;
                                    userInfo.Email       = email;

                                    UserController.UpdateUser(PortalSettings.PortalId, userInfo);

                                    //We update the user's properties
                                    SetProfileProperties(samlResponse, userInfo);

                                    //Ensure roles if neeeded
                                    if (rolesList.Any())
                                    {
                                        AssignRolesFromList(userInfo, rolesList);
                                    }

                                    //If we have a required role list, remove any of those items that were not in the SAML attribute
                                    if (requiredRolesList.Any())
                                    {
                                        var toRemove = requiredRolesList.Where(req => !rolesList.Contains(req))
                                                       .ToList();
                                        RemoveRolesFromList(userInfo, toRemove);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "Error updating existing user...exception:  " + ex.InnerException.Message);
                                }
                            }


                            UserValidStatus validStatus = UserController.ValidateUser(userInfo, PortalId, true);
                            UserLoginStatus loginStatus = validStatus == UserValidStatus.VALID ? UserLoginStatus.LOGIN_SUCCESS : UserLoginStatus.LOGIN_FAILURE;
                            if (loginStatus == UserLoginStatus.LOGIN_SUCCESS)
                            {
                                SetLoginDate(username);
                                //Raise UserAuthenticated Event
                                var eventArgs = new UserAuthenticatedEventArgs(userInfo, userInfo.Email, loginStatus, config.DNNAuthName) //"DNN" is default, "SAML" is this one.  How did it get named SAML????
                                {
                                    Authenticated = true,
                                    Message       = "User authorized",
                                    RememberMe    = false
                                };
                                OnUserAuthenticated(eventArgs);
                            }
                        }
                        else
                        {
                            LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", "saml not valid");
                        }
                    }
                    else if (Request.IsAuthenticated)
                    {
                        //Do Nothing if the request is authenticated
                    }
                    else
                    {
                        XmlDocument request = GenerateSAMLRequest();
                        //X509Certificate2 cert = StaticHelper.GetCert(config.OurCertFriendlyName);
                        //request = StaticHelper.SignSAMLRequest(request, cert);
                        LogToEventLog("DNN.Authentication.SAML.OnLoad()", string.Format("request xml {0}", request.OuterXml));
                        String convertedRequestXML = StaticHelper.Base64CompressUrlEncode(request);
                        redirectTo = config.IdPURL + (config.IdPURL.Contains("?") ? "&" : "?") + "SAMLRequest=" + convertedRequestXML;
                        if (Request.QueryString.Count > 0)
                        {
                            redirectTo += "&RelayState=" + HttpUtility.UrlEncode(Request.Url.Query.Replace("?", "&"));
                        }

                        Response.Redirect(Page.ResolveUrl(redirectTo), false);
                    }
                }
                catch (System.Threading.ThreadAbortException tae)
                {
                    LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("Exception is {0}", tae.Message));
                    //Response.Redirect(Page.ResolveUrl(redirectTo), false);
                }
                catch (Exception ex)
                {
                    LogToEventLog("DNN.Authentication.SAML.OnLoad()", string.Format("Exception  {0}", ex.Message));
                    //redirectTo = "~/";
                }

                //Response.Redirect(Page.ResolveUrl(redirectTo), false);
            }
        }
Exemple #4
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            staticPortalSettings = PortalSettings;
            string redirectTo = "~/";

            try
            {
                config = DNNAuthenticationSAMLAuthenticationConfig.GetConfig(PortalId);
                if (Request.HttpMethod == "POST" && !Request.IsAuthenticated)
                {
                    if (Request.Form["RelayState"] != null)
                    {
                        string relayState = HttpUtility.UrlDecode(Request.Form["RelayState"]);
                        LogToEventLog("DNN.Authentication.SAML.OnLoad(post !auth)", string.Format("relayState : {0}", relayState));
                        var relayStateSplit = relayState.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string s in relayStateSplit)
                        {
                            if (s.ToLower().StartsWith("returnurl"))
                            {
                                redirectTo = "~" + s.Replace("returnurl=", "");
                                break;
                            }
                        }
                    }


                    X509Certificate2          myCert = StaticHelper.GetCert(config.OurCertFriendlyName);
                    System.Text.ASCIIEncoding enc    = new System.Text.ASCIIEncoding();
                    string          responseXML      = enc.GetString(Convert.FromBase64String(Request.Form["SAMLResponse"]));
                    ResponseHandler responseHandler  = new ResponseHandler(responseXML, myCert,
                                                                           config.TheirCert
                                                                           );

                    LogToEventLog("DNN.Authentication.SAML.OnLoad(post !auth)", "responseXML : " + responseHandler.ResponseString());


                    string   emailFromSAMLResponse = responseHandler.GetNameID();
                    UserInfo userInfo = UserController.GetUserByName(PortalSettings.PortalId, emailFromSAMLResponse);
                    if (userInfo == null)
                    {
                        userInfo                     = new UserInfo();
                        userInfo.Username            = emailFromSAMLResponse;
                        userInfo.PortalID            = base.PortalId;
                        userInfo.DisplayName         = emailFromSAMLResponse;
                        userInfo.Email               = emailFromSAMLResponse;
                        userInfo.FirstName           = emailFromSAMLResponse;
                        userInfo.LastName            = emailFromSAMLResponse;
                        userInfo.Membership.Password = UserController.GeneratePassword(12).ToString();

                        UserCreateStatus rc = UserController.CreateUser(ref userInfo);
                        if (rc == UserCreateStatus.Success)
                        {
                            addRoleToUser(userInfo, "Subscribers", DateTime.MaxValue);
                        }
                    }
                    else
                    {
                        LogToEventLog("DNN.Authentication.SAML.OnLoad(post !auth)", String.Format("FoundUser userInfo.Username: {0}", userInfo.Username));
                    }


                    string sessionIndexFromSAMLResponse = responseHandler.GetSessionIndex();
                    Session["sessionIndexFromSAMLResponse"] = sessionIndexFromSAMLResponse;


                    UserValidStatus validStatus = UserController.ValidateUser(userInfo, PortalId, true);
                    UserLoginStatus loginStatus = validStatus == UserValidStatus.VALID ? UserLoginStatus.LOGIN_SUCCESS : UserLoginStatus.LOGIN_FAILURE;
                    if (loginStatus == UserLoginStatus.LOGIN_SUCCESS)
                    {
                        //Raise UserAuthenticated Event
                        var eventArgs = new UserAuthenticatedEventArgs(userInfo, userInfo.Email, loginStatus, config.DNNAuthName) //"DNN" is default, "SAML" is this one.  How did it get named SAML????
                        {
                            Authenticated = true,
                            Message       = "User authorized",
                            RememberMe    = false
                        };
                        OnUserAuthenticated(eventArgs);
                    }
                }
                else if (Request.IsAuthenticated)
                {
                    //if (!Response.IsRequestBeingRedirected)
                    //    Response.Redirect(Page.ResolveUrl("~/"), false);
                }
                else
                {
                    XmlDocument      request = GenerateSAMLRequest();
                    X509Certificate2 cert    = StaticHelper.GetCert(config.OurCertFriendlyName);
                    request = StaticHelper.SignSAMLRequest(request, cert);
                    LogToEventLog("DNN.Authentication.SAML.OnLoad()", string.Format("request xml {0}", request.OuterXml));
                    String convertedRequestXML = StaticHelper.Base64CompressUrlEncode(request);
                    redirectTo =
                        config.IdPURL +
                        (config.IdPURL.Contains("?") ? "&" : "?") +
                        "SAMLRequest=" + convertedRequestXML;
                    if (Request.QueryString.Count > 0)
                    {
                        redirectTo += "&RelayState=" + HttpUtility.UrlEncode(Request.Url.Query.Replace("?", "&"));
                    }
                }
            }
            catch (System.Threading.ThreadAbortException tae)
            {
                LogToEventLog("DNN.Authentication.SAML.OnLoad(tae)", string.Format("Redirecting to  {0}", redirectTo));
                Response.Redirect(Page.ResolveUrl(redirectTo), false);
            }
            catch (Exception ex)
            {
                LogToEventLog("DNN.Authentication.SAML.OnLoad()", string.Format("Exception  {0}", ex.Message));
                redirectTo = "~/";
            }

            Response.Redirect(Page.ResolveUrl(redirectTo), false);
        }