Example #1
0
        private void SetProfileProperties(Saml.Response response, UserInfo uInfo)
        {
            try
            {
                Dictionary <string, string>         properties = new Dictionary <string, string>();
                ProfilePropertyDefinitionCollection props      = ProfileController.GetPropertyDefinitionsByPortal(PortalSettings.PortalId);
                foreach (ProfilePropertyDefinition def in props)
                {
                    string SAMLPropertyName = config.getProfilePropertySAMLName(def.PropertyName);
                    if (SAMLPropertyName != "")
                    {
                        properties.Add(def.PropertyName, response.GetUserProperty(SAMLPropertyName));
                    }
                }

                foreach (KeyValuePair <string, string> kvp in properties)
                {
                    uInfo.Profile.SetProfileProperty(kvp.Key, kvp.Value);
                }

                ProfileController.UpdateUserProfile(uInfo);
            }
            catch (Exception exc)
            {
                LogToEventLog("DNN.Authentication.SAML.SetProfileProperties", string.Format("Exception  {0}", exc.Message));
            }
        }
Example #2
0
        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);
            }
        }