Esempio n. 1
0
        /// <summary>
        /// Initialize the Group
        /// </summary>
        /// <returns></returns>
        public Group New(Saml.Response samlResponse)
        {
            if (samlResponse != null)
            {
                NameValueCollection att = samlResponse.GetAttributes();

                // General info
                Uid           = att["group_uid"];
                Name          = att["group_name"];
                Email         = att["group_email"];
                CompanyName   = att["company_name"];
                HasCreditCard = att["group_has_credit_card"].Equals("true");

                // Set Free trial in the past on failure
                try
                {
                    FreeTrialEndAt = DateTime.Parse(att["group_end_free_trial"]);
                }
                catch
                {
                    FreeTrialEndAt = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                }

                // Geo info
                Currency = att["group_currency"];
                Timezone = TimeZoneConverter.fromOlsonTz(att["group_timezone"]);
                Country  = att["group_country"];
                City     = att["group_city"];
            }

            return(this);
        }
Esempio n. 2
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));
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Constructor loading group attributes from a Saml.Response
        /// </summary>
        /// <param name="samlResponse"></param>
        public Membership(Saml.Response samlResponse)
        {
            NameValueCollection att = samlResponse.GetAttributes();

            UserUid  = att["uid"];
            GroupUid = att["group_uid"];
            Role     = att["group_role"];
        }
Esempio n. 4
0
        /// <summary>
        /// Build a Saml Response object from a base64 encoded response
        /// </summary>
        /// <param name="samlPostParam">The value of the SAMLResponse POST parameter</param>
        /// <returns></returns>
        public Saml.Response BuildResponse(String samlPostParam)
        {
            var resp = new Saml.Response();

            resp.LoadXmlFromBase64(samlPostParam);

            return(resp);
        }
Esempio n. 5
0
        /// <summary>
        /// Constructor loading user attributes from a Saml.Response
        /// </summary>
        /// <param name="samlResponse"></param>
        public User(Saml.Response samlResponse)
        {
            NameValueCollection att = samlResponse.GetAttributes();

            SsoSession        = att["mno_session"];
            SsoSessionRecheck = DateTime.Parse(att["mno_session_recheck"]);
            GroupUid          = att["group_uid"];
            GroupRole         = att["group_role"];
            Uid          = att["uid"];
            VirtualUid   = att["virtual_uid"];
            Email        = att["email"];
            VirtualEmail = att["virtual_email"];
            FirstName    = att["name"];
            LastName     = att["surname"];
            Country      = att["country"];
            CompanyName  = att["company_name"];
        }
Esempio n. 6
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);
            }
        }
Esempio n. 7
0
        public ActionResult EmmsACS()
        {
            User user = new User();

            try
            {
                string cer = certificate;

                Saml.Response samlResponse = new Saml.Response(cer);

                samlResponse.LoadXmlFromBase64(Request.Form["SAMLResponse"]);

                if (samlResponse.IsValid())
                {
                    try
                    {
                        user.UserName  = samlResponse.GetNameID();
                        user.email     = samlResponse.GetEmail();
                        user.firstname = samlResponse.GetFirstName();
                        user.lastname  = samlResponse.GetLastName();
                        user.country   = samlResponse.GetCountry();


                        //    user.UserName = "******";
                        //user.email = "*****@*****.**";
                        //user.firstname = "YP";
                        //user.lastname = "YP";
                        //user.country = "in";
                        //emaialID = "*****@*****.**";

                        emaialID            = user.email;
                        Session["EmailiID"] = emaialID;
                        Session["UserName"] = user.UserName;
                        Session["EmailiID"] = emaialID;
                        List <Assets> asetsList = plantSetup.GetUserDetails((emaialID).Trim());
                        if (asetsList == null)
                        {
                            return(RedirectToAction("ErrorMsg", "Auth"));
                        }
                        if (asetsList.Count > 1)
                        {
                            int roleId = 0;
                            foreach (var item in asetsList)
                            {
                                roleId = asetsList.Max(r => r.RoleId);
                            }
                            Session["RoleId"] = roleId;
                            return(RedirectToAction("PlantList", "Auth"));
                        }
                        else if (asetsList.Count > 0)
                        {
                            int roleId = 0;
                            foreach (var item in asetsList)
                            {
                                roleId               = asetsList.Max(r => r.RoleId);
                                Session["PlantId"]   = item.PlantID;
                                Session["PlantName"] = item.PlantName;
                            }
                            Session["RoleId"] = roleId;
                            if (Session["PlantId"].ToString() == "0" && Session["RoleId"].ToString() == "2")
                            {
                                return(RedirectToAction("adminConfiguration", "Admin"));
                            }
                            else
                            {
                                if ((Session["PlantId"].ToString() == "0" && Session["RoleId"].ToString() == "1"))
                                {
                                    return(RedirectToAction("PlantErrorMsg", "Auth"));
                                }
                                else
                                {
                                    return(RedirectToAction("HomePage", "HomePage"));
                                }
                            }
                        }
                        else
                        {
                            return(RedirectToAction("ErrorMsg", "Auth"));
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Log("error in AddAcutalInputConsumption" + ex.ToString());
                        //insert error handling code
                        //no, really, please do
                        user.Error = ex.Message;
                    }
                }
                else
                {
                    user.Error = "Valid Failed....";
                }
            }
            catch (Exception ex)
            {
                user.Error = "Initial Fail";
                return(RedirectToAction("ErrorMsg", "Auth"));
            }

            return(RedirectToAction("ErrorMsg", "Auth"));
        }
Esempio n. 8
0
 /// <summary>
 /// Constructor loading group attributes from a Saml.Response
 /// </summary>
 /// <param name="samlResponse"></param>
 public Group(Saml.Response samlResponse = null)
 {
     this.New(samlResponse);
 }
Esempio n. 9
0
        /// <summary>
        /// Build a Saml Response object from a base64 encoded response
        /// </summary>
        /// <param name="samlPostParam">The value of the SAMLResponse POST parameter</param>
        /// <returns></returns>
        public Saml.Response BuildResponse(String samlPostParam)
        {
            var resp = new Saml.Response();
            resp.LoadXmlFromBase64(samlPostParam);

            return resp;
        }
Esempio n. 10
0
 /// <summary>
 /// Constructor loading user attributes from a Saml.Response
 /// </summary>
 /// <param name="samlResponse"></param>
 public User(Saml.Response samlResponse = null)
 {
     this.New(samlResponse);
 }