Umbraco 7个自定义会员和角色提供者

时间:2015-04-17 16:10:34

标签: .net umbraco membership-provider umbraco7 roleprovider

我浏览了10个文档,我正在做正确的事情,但我确信这是我遗漏的一个小细节。

我想使用自己的登录机制登录我的网站。登录机制位于Identity服务器中以进行单点登录。

但我想在umbraco中使用公共访问功能,所以我从本地数据库添加角色。通过更改配置文件

<roleManager enabled="true" defaultProvider="UmbracoRoleProvider">
      <providers>
        <clear />
        <add name="UmbracoRoleProvider" type="rcsedWebServiceBLL.RCSEdRoleProvider" />
      </providers>
    </roleManager>

并实施RoleProvider

 class RCSEdRoleProvider : RoleProvider
    {
        private string _ApplicationName = "UmbracoRoleProvider";
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
        throw new NotImplementedException();
    }

    public override string ApplicationName
    {
        get { return _ApplicationName; }
        set
        {
            if(string.IsNullOrEmpty(value))
                throw new ProviderException("ApplicationName Cacnnot be Empty");

            if(value.Length > 0x100)
                throw new ProviderException("provider application name too long");

            _ApplicationName = value;
        }
    }

    public override void CreateRole(string roleName)
    {
        throw new NotImplementedException();
    }

    public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
    {
        throw new NotImplementedException();
    }

    public override string[] FindUsersInRole(string roleName, string usernameToMatch)
    {
        throw new NotImplementedException();
    }

    public override string[] GetAllRoles()
    {
        return UBISRoles.GetRoleList();
    }

    public override string[] GetRolesForUser(string username)
    {
        // code to return user role access
        try
        {
           //ool isAuthenticateSession = RCSEd.UolsSecurity.CommonFunctions.CheckAuthenticateSessionOrNot();

            if (HttpContext.Current.Session["UOSStudent"] != null)
            {
                return (String[])HttpContext.Current.Session["userRoles"];
            }
            else
            {
                List<String> retval = new List<string>();
                retval.Add("Public");
                return retval.ToArray();
            }
        }
        catch (Exception ex)
        {
           // AppLogWriter _objApplog = new AppLogWriter();
           // _objApplog.WriteLogMessages(ex.Message.ToString());
            //TODO catch Error 
            List<String> retval = new List<string>();
            retval.Add("Public");
            return retval.ToArray();
        }

    }

    public override string[] GetUsersInRole(string roleName)
    {
        throw new NotImplementedException();
    }

    public override bool IsUserInRole(string username, string roleName)
    {
        try
        {
            foreach (String role in (String[])HttpContext.Current.Session["userRoles"])
            {
                if (String.Compare(role, roleName, true) == 0)
                    return true;
            }


            return false;

        }
        catch { }

        return false;

    }

    public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
    {
        throw new NotImplementedException();
    }

    public override bool RoleExists(string roleName)
    {

        foreach (string val in UBISRoles.GetRoleList())
        {
            if (val == roleName)
                return true;
        }

        return false;
    }
}

class UBISRoles
{
    private static string[] allroles = new string[] { //"Public", 
     "MembershipCandidate",
        "MembershipMember"
      };


    public static string[] GetRoleList()
    {
        return allroles;
    }



    public static void SetRoles(DataTable UBIsRolesResultsTBL)
    {
        List<String> userRoles = new List<string>();

        DataRow rec = UBIsRolesResultsTBL.Rows[0];


        switch (rec["Membership"].ToString())
        {

            case "member":
                userRoles.Add("MembershipMember");
                break;
            case "pending member":
                userRoles.Add("MembershipPending");//add
                break;
            case "public":
                userRoles.Add("MembershipPublic");//add
                break;

        }






        HttpContext.Current.Session["userRoles"] = userRoles.ToArray();

    }

    private static void CheckSimpleFieldVal(List<String> userRoles, DataRow rec, string roleName)
    {
        try
        {
            if (string.Compare(rec[roleName].ToString(), "YES", true) == 0)
                userRoles.Add(roleName);

        }
        catch (Exception ex)
        {
            string msg = ex.Message;

        }

    }

    private static void CheckSimpleFieldValV2(List<String> userRoles, DataRow rec, string roleName)
    {
        try
        {
            if (string.Compare(rec[roleName].ToString(), "1", true) == 0)
                userRoles.Add(roleName);

        }
        catch (Exception ex)
        {
            string msg = ex.Message;

        }

    }

}

这样可以正常工作,所有内容都在umbraco后台的成员组中加载。

但是当我尝试实现MembershipProvider时,我觉得事情不起作用。 web配置看起来像这样

  <membership defaultProvider="UmbracoMembershipProvider" userIsOnlineTimeWindow="15">
      <providers>
        <clear />
        <add name="UmbracoMembershipProvider" type="rcsedWebServiceBLL.RCSEdMembershipProvide"  />
        <add name="UsersMembershipProvider" type="Umbraco.Web.Security.Providers.UsersMembershipProvider, Umbraco" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="4" useLegacyEncoding="true" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" passwordFormat="Hashed" />
      </providers>
    </membership>

Membershiprovider类看起来像这样

class RCSEdMembershipProvide : MembershipProvider
    {
        string connectionStringName;
        private string _ApplicationName =  "UmbracoMembershipProvider";
        public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
        {
        base.Initialize(name, config);

      /*  if (config["ConnectionStringName"] != null)
            connectionStringName = config["connectionStringName"];*/




    }

    public override string ApplicationName
    {
        get { return _ApplicationName; }
        set
        {
            if (string.IsNullOrEmpty(value))
                throw new ProviderException("ApplicationName Cacnnot be Empty");

            if (value.Length > 0x100)
                throw new ProviderException("provider application name too long");

            _ApplicationName = value;
        }
    }

    public override bool ChangePassword(string username, string oldPassword, string newPassword)
    {
        throw new NotImplementedException();
    }

    public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
    {
        throw new NotImplementedException();
    }

    public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
    {
        throw new NotImplementedException();
    }

    public override bool DeleteUser(string username, bool deleteAllRelatedData)
    {
        throw new NotImplementedException();
    }

    public override bool EnablePasswordReset
    {
        get { throw new NotImplementedException(); }
    }

    public override bool EnablePasswordRetrieval
    {
        get { throw new NotImplementedException(); }
    }

    public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
    {
        throw new NotImplementedException();
    }

    public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
    {
        throw new NotImplementedException();
    }

    public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
    {
        throw new NotImplementedException();
    }

    public override int GetNumberOfUsersOnline()
    {
        throw new NotImplementedException();
    }

    public override string GetPassword(string username, string answer)
    {
        throw new NotImplementedException();
    }

    public override MembershipUser GetUser(string username, bool userIsOnline)
    {
        try
        {
            User user = (User)HttpContext.Current.Session["user"];
            if (user != null)
                return new MembershipUser("RCSEdMembershipProvider", user.DisplayName, username, user.Email, "", "", true, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now);
            else
                return null;

        }
        catch
        {
            return null;
        }
    }

    public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
    {
        try
        {
            User user = (User)HttpContext.Current.Session["user"];

            if (user != null)
                return new MembershipUser("RCSEdMembershipProvider", user.DisplayName, providerUserKey, user.Email, "", "", true, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now);
            else
                return null;
        }
        catch
        {

            return null;
        }
    }

    public override string GetUserNameByEmail(string email)
    {
        throw new NotImplementedException();
    }

    public override int MaxInvalidPasswordAttempts
    {
        get { throw new NotImplementedException(); }
    }

    public override int MinRequiredNonAlphanumericCharacters
    {
        get { throw new NotImplementedException(); }
    }

    public override int MinRequiredPasswordLength
    {
        get { throw new NotImplementedException(); }
    }

    public override int PasswordAttemptWindow
    {
        get { throw new NotImplementedException(); }
    }

    public override MembershipPasswordFormat PasswordFormat
    {
        get { throw new NotImplementedException(); }
    }

    public override string PasswordStrengthRegularExpression
    {
        get { throw new NotImplementedException(); }
    }

    public override bool RequiresQuestionAndAnswer
    {
        get { throw new NotImplementedException(); }
    }

    public override bool RequiresUniqueEmail
    {
        get { throw new NotImplementedException(); }
    }

    public override string ResetPassword(string username, string answer)
    {
        throw new NotImplementedException();
    }

    public override bool UnlockUser(string userName)
    {
        throw new NotImplementedException();
    }

    public override void UpdateUser(MembershipUser user)
    {
        throw new NotImplementedException();
    }

    public override bool ValidateUser(string username, string password)
    {


        return true;
    }
}

我甚至一直将validateUser视为真实。

因此,当用户登录我的身份服务器时,我在HttpContext.Current.Session["userRoles"]中加载了用户角色,并限制了我的页面的公共访问权限,并将用户重定向到正确的页面。

当用户未登录时,用户被重定向到登录页面,但是当用户被退回并且他/她的角色被加载并尝试访问受限页面时,会员提供者ValidateUser不能被点击,用户被一次又一次地重定向回登录页面。

PS。我正在使用umbraco 7.1.3

请原谅这个冗长的问题,但我想完成我的所有步骤。提前谢谢你。

1 个答案:

答案 0 :(得分:1)

不能'评论所以它会回答:)希望这会有所帮助。我的示例基于用户使用umbraco登录,并且您希望外部提供程序处理成员身份登录。如果是另一种方式我道歉。

我在umbraco 7.2中同时拥有角色提供者和用户提供者。我希望您可以使用我的实现进行比较。它对我有用。

Web.config看起来像:

<membership defaultProvider="UmbracoMembershipProvider" userIsOnlineTimeWindow="15">
      <providers>
        <clear/>
        <!--<add name="UmbracoMembershipProvider" type="Umbraco.Web.Security.Providers.MembersMembershipProvider, Umbraco" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="4" useLegacyEncoding="true" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" defaultMemberTypeAlias="Member" passwordFormat="Hashed" />-->
        <add name="UsersMembershipProvider" type="Umbraco.Web.Security.Providers.UsersMembershipProvider, Umbraco" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="4" useLegacyEncoding="true" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" passwordFormat="Hashed"/>
        <add name="UmbracoMembershipProvider" type="XXX.Model.Membership.SAPMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" defaultMemberTypeAlias="_umbracoSystemDefaultProtectType" passwordFormat="Hashed"/>
      </providers>
    </membership>
    <!-- Role Provider -->
    <roleManager enabled="true" defaultProvider="UmbracoRoleProvider">
      <providers>
        <clear/>
        <add name="UmbracoRoleProvider" type="XXX.Model.Membership.SAPRoleProvider"/>
        <!--<add name="UmbracoRoleProvider" type="Umbraco.Web.Security.Providers.MembersRoleProvider"/>-->
      </providers>
    </roleManager>

我的角色提供程序看起来像这样

    public class SAPRoleProvider : Umbraco.Web.Security.Providers.MembersRoleProvider
        {

            public override bool IsUserInRole(string username, string roleName)
            {
                if (roleName.ToLower() == "standard")
                    return true;
                else
                    return base.IsUserInRole(username, roleName);
            }
            public override string[] GetRolesForUser(string username)
            {
                return new[] { "Standard" };
            }
        }

和会员提供商这样:

public class SAPMembershipProvider : Umbraco.Web.Security.Providers.UsersMembershipProvider
    {
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            ILoginService Loginss = new LoginService();
            return Loginss.ChangePassword(oldPassword, newPassword, username);
        }
        public override string ResetPassword(string username, string answer)
        {
            ILoginService Loginss = new LoginService();
            return Loginss.ResetPassword(username).ToString();
        }
        public override MembershipUser GetUser(object providerUserKey, bool someonelinestuff)
        {
            return GetSapUser(providerUserKey);
        }


        /// <summary>
        /// It is not the username but providerUserKey i ask for herem just to test since I am not sure what SAP want right now, regarding request of userdata
        /// </summary>
        /// <param name="providerUserKey"></param>
        /// <param name="someonelinestuff"></param>
        /// <returns></returns>
        public override MembershipUser GetUser(string username, bool someonelinestuff)
        {
            return GetSapUser(username);
        }
        public SAPMembershipUser GetUser(string username)
        {
            return (SAPMembershipUser)GetUser(username, false);
        }

        public override bool ValidateUser(string username, string password)
        {
            try
            {
                ILoginService LoginS = new LoginService();
                SAPMembershipUser SU = LoginS.Login(username, password);
                if (SU != null)
                {
                    FrieLib.CacheHelper.StoreCache(username.ToLower(), SU,true,20);
                    return true;
                }
            }
            catch { return false; }
            return false;
        }


        protected override bool PerformChangePassword(string username, string oldPassword, string newPassword)
        {
            ILoginService Loginss = new LoginService();
            return Loginss.ChangePassword(oldPassword, newPassword, username);
        }
        private SAPMembershipUser GetSapUser(string username)
        {

            try
            {
                SAPMembershipUser SU = (SAPMembershipUser)FrieLib.CacheHelper.RetrieveCache(username.ToLower());
                if (SU != null)
                {
                    return SU;
                }
                else
                {
                    HttpContext.Current.Response.Redirect("/umbraco/Surface/MemberLoginSurface/MemberLogout");
                }

            }
            catch (Exception es)
            {
                HttpContext.Current.Response.Redirect("/umbraco/Surface/MemberLoginSurface/MemberLogout");
            }
            return null;
        }
        private SAPMembershipUser GetSapUser(object providerUserKey)
        {
            return GetSapUser(providerUserKey.ToString());
        }
    }

我还有一个额外的步骤,我不知道你是否遗漏了我确保最终用户登录的地方。

[HttpPost]
        [ActionName("MemberLogin")]
        public ActionResult MemberLoginPost(MemberLoginModel model)
        {
            if (Membership.ValidateUser(model.Username, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.Username.ToLower(), model.RememberMe);

                    return RedirectToCurrentUmbracoUrl();
            }
            else
            {
                TempData["Status"] = "danger";
                TempData["StatusMessage"] = "login_fail_message";
                return RedirectToCurrentUmbracoPage();
            }
        }

我希望它有所帮助。