ASP.NET MVC3 和 EF4.1 - 如何在运行 aspnet_regsql 后自定义成员资格?

发布于 2024-12-03 10:44:53 字数 599 浏览 0 评论 0原文

我需要在我的社交网络应用程序中实现自定义会员资格,并将信息添加到现有数据库中的常规 aspnet 表中,如国家、省份、城市、出生日期等。

我已经根据这篇文章运行了 aspnet_regsql <一href="https://stackoverflow.com/questions/3861721/add-asp-net-membership-tables-to-my-own-existing-database-or-should-i-instead-con">添加 ASP.NET将成员表添加到我自己的现有数据库中,或者我应该配置一个单独的 ASP.NET 成员资格数据库? 并已尝试按照此帖子http://msdn.microsoft.com/en-us/library/ms366730。 aspx#Y342 但我从重写方法中得到了一些构建错误,实际上我想找到任何使用 MVC 3 和EF4.1。

无论如何,运行 aspnet_regsql 后,实施自定义成员资格方法的下一步是什么?您知道有什么分步(简单)教程可以帮助我吗?谢谢你们!

I need to implement in my social network application a customized membership, and add information to the regular aspnet tables in an existing database, as Country, Province, City, Birthdate, etc, etc, etc.

I already ran aspnet_regsql, based on this post Add ASP.NET Membership tables to my own existing database, or should I instead configure a separate ASP.NET membership database? and already tried to follow this post http://msdn.microsoft.com/en-us/library/ms366730.aspx#Y342 but I got some build errors from the overriden methods, and actualy I would like to find any example step-by-step using MVC 3 and EF4.1.

Anyway, after run aspnet_regsql, what would be the next step to implement customized membership methods? Do you know any step-by-step (easy) tutorial to help me? Thank you guys!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

星星的轨迹 2024-12-10 10:44:53

将其他用户数据存储在您自己的用户表中。存储您想要的任何其他字段,并包括一个允许您将记录与会员用户关联起来的字段。远离会员资格表,仅通过会员资格提供商访问它们,以避免处理 Microsoft 将来可能在幕后进行的任何更改。

Store your additional user data in your own Users table. Store any additional fields you want and include one field that will allow you to relate the record back to a membership User. Stay out of the Membership tables and only access them through the Membership provider to avoid dealing with any changes Microsoft may make under the hood in the future.

南巷近海 2024-12-10 10:44:53

如果您想下载一些代码来看看它是如何完成的,您可以使用 nerdinner 的: http://nerddinner.codeplex.com/< /a>

首先,您需要确保 web.config 配置正确

<connectionStrings>
     <add name="XXXXXMembership" connectionString="data source=.\SQLEXPRESS;Initial Catalog=corpiq_membership;User Id=corpiq; Password=c0rp1q; Persist Security Info=true;" providerName="System.Data.SqlClient" />
     <add name="CorpiqDb" connectionString="data source=.\SQLEXPRESS;Initial Catalog=corpiq;User Id=corpiq; Password=c0rp1q; Persist Security Info=true;" providerName="System.Data.SqlClient" />
  </connectionStrings>

<membership>
      <providers>
        <clear/>
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="XXXXXMembership"
             enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true"
             maxInvalidPasswordAttempts="3" minRequiredPasswordLength="8" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="30"
             passwordStrengthRegularExpression="^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$" passwordFormat="Hashed" applicationName="/" />
      </providers>
    </membership>

如果一切正常,您应该能够启动 ASP.Net 配置工具,女巫就是解决方案顶部的锤子(红色)和行星当您访问 MVC 网站时,请使用资源管理器。使用该工具,您可以添加用户和角色。

在您应该能够简单地在控制器中添加这一行之后:

[Authorize(Roles = "Member, Delegate")]

我建议编写一个调用成员方法的包装器,以便您可以拥有自己的逻辑,这是我的:

public class AuthenticationService : IAuthenticationService
    {

        public bool IsValidLogin(string email, string password)
        {
            //Unlock user if it makes more than 30 minutes
            CheckLocked(email);
            return Membership.ValidateUser(email, password);
        }

        public void SignIn(string email, bool createPersistentCookie)
        {
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
            FormsAuthentication.SetAuthCookie(email, createPersistentCookie);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }

        public string GetLoggedInUserName()
        {
            return Membership.GetUser() != null ? Membership.GetUser().UserName : string.Empty;
        }

        public MembershipCreateStatus RegisterUser(string email, string password, string role)
        {
            MembershipCreateStatus status;
            Membership.CreateUser(email, password, email, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), true, out status);

            if (status == MembershipCreateStatus.Success)
            {
                Roles.AddUserToRole(email, role);
            }
            return status;
        }

        public MembershipUserCollection GetAllUsers()
        {
            return Membership.GetAllUsers();
        }

        public string GeneratePassword()
        {
            var alphaCaps = "QWERTYUIOPASDFGHJKLZXCVBNM";
            var alphaLow = "qwertyuiopasdfghjklzxcvbnm";
            var numerics = "1234567890";
            var special = "@#$";
            var allChars = alphaCaps + alphaLow + numerics + special;
            var r = new Random();
            var generatedPassword = "";
            for (int i = 0; i < MinPasswordLength - 1; i++)
            {
                double rand = r.NextDouble();
                if (i == 0)
                {
                    //First character is an upper case alphabet
                    generatedPassword += alphaCaps.ToCharArray()[(int)Math.Floor(rand * alphaCaps.Length)];
                    //Next one is numeric
                    rand = r.NextDouble();
                    generatedPassword += numerics.ToCharArray()[(int) Math.Floor(rand*numerics.Length)];
                }
                else
                {
                    generatedPassword += allChars.ToCharArray()[(int)Math.Floor(rand * allChars.Length)];
                }
            }
            return generatedPassword;
        }

        public int MinPasswordLength
        {
            get
            {
                return Membership.Provider.MinRequiredPasswordLength;
            }
        }

        public string AdminRole
        {
            get { return "admin"; }
        }

        public string MemberRole
        {
            get { return "member"; }
        }

        public string DelegateRole
        {
            get { return "delegate"; }
        }

        public bool Delete(string email)
        {
            return Membership.DeleteUser(email);
        }

        public bool IsAdmin()
        {
            return Roles.IsUserInRole(AdminRole);
        }

        public bool IsMember()
        {
            return Roles.IsUserInRole(MemberRole);
        }

        public bool IsDelegate()
        {
            return Roles.IsUserInRole(DelegateRole);
        }

        public bool ChangePassword(string email, string oldPassword, string newPassword)
        {
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
            if (String.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Value cannot be null or empty.", "oldPassword");
            if (String.IsNullOrEmpty(newPassword)) throw new ArgumentException("Value cannot be null or empty.", "newPassword");

            // The underlying ChangePassword() will throw an exception rather
            // than return false in certain failure scenarios.
            try
            {
                var currentUser = Membership.Provider.GetUser(email, true);
                return currentUser.ChangePassword(oldPassword, newPassword);
            }
            catch (ArgumentException)
            {
                return false;
            }
            catch (MembershipPasswordException)
            {
                return false;
            }
        }

        public string ResetPassword(string email)
        {
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
            var currentUser = Membership.Provider.GetUser(email, false);
            return currentUser.ResetPassword();
        }

        public bool CheckLocked(string email)
        {
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
            var currentUser = Membership.Provider.GetUser(email, false);
            if (currentUser == null) return false;
            if (!currentUser.IsLockedOut) return false;
            if (currentUser.LastLockoutDate.AddMinutes(30) < DateTime.Now)
            {
                currentUser.UnlockUser();
                return false;
            }
            return true;
        }

        public bool Unlock(string email)
        {
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
            var currentUser = Membership.Provider.GetUser(email, false);
            if (currentUser == null) return false;
            currentUser.UnlockUser();
            return true;
        }

        public void CheckRoles()
        {
            if (!Roles.RoleExists(MemberRole)) Roles.CreateRole(MemberRole);
            if (!Roles.RoleExists(AdminRole)) Roles.CreateRole(AdminRole);
            if (!Roles.RoleExists(DelegateRole)) Roles.CreateRole(DelegateRole);
        }
}

我不太确定您不理解的部分,但是让我们详细知道您有什么问题,也许我们可以提供更多帮助!我认为你需要首先构建代码。

这是 EF 的良好开端(这样您就可以在自己的数据库中编写自定义配置文件/用户): http://weblogs.asp.net/scottgu/archive/2010/08/03/using-ef-code-first-with-an-existing-database.aspx

If you want to download some code to look how it's done you can take nerdinner's : http://nerddinner.codeplex.com/

First you need to have to be sure youre web.config configuration is ok

<connectionStrings>
     <add name="XXXXXMembership" connectionString="data source=.\SQLEXPRESS;Initial Catalog=corpiq_membership;User Id=corpiq; Password=c0rp1q; Persist Security Info=true;" providerName="System.Data.SqlClient" />
     <add name="CorpiqDb" connectionString="data source=.\SQLEXPRESS;Initial Catalog=corpiq;User Id=corpiq; Password=c0rp1q; Persist Security Info=true;" providerName="System.Data.SqlClient" />
  </connectionStrings>

<membership>
      <providers>
        <clear/>
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="XXXXXMembership"
             enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true"
             maxInvalidPasswordAttempts="3" minRequiredPasswordLength="8" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="30"
             passwordStrengthRegularExpression="^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$" passwordFormat="Hashed" applicationName="/" />
      </providers>
    </membership>

If everything is ok you should be able to launch the ASP.Net Configuration tool, witch is th hammer (in red) and planet on top of the solution explorer when you are on the MVC website. With that tools you can add user and roles.

After you should be able to simply add this line in your controller :

[Authorize(Roles = "Member, Delegate")]

And I would suggest writing a wrapper that call Membership method so you can have youre own logic, here's mine :

public class AuthenticationService : IAuthenticationService
    {

        public bool IsValidLogin(string email, string password)
        {
            //Unlock user if it makes more than 30 minutes
            CheckLocked(email);
            return Membership.ValidateUser(email, password);
        }

        public void SignIn(string email, bool createPersistentCookie)
        {
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
            FormsAuthentication.SetAuthCookie(email, createPersistentCookie);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }

        public string GetLoggedInUserName()
        {
            return Membership.GetUser() != null ? Membership.GetUser().UserName : string.Empty;
        }

        public MembershipCreateStatus RegisterUser(string email, string password, string role)
        {
            MembershipCreateStatus status;
            Membership.CreateUser(email, password, email, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), true, out status);

            if (status == MembershipCreateStatus.Success)
            {
                Roles.AddUserToRole(email, role);
            }
            return status;
        }

        public MembershipUserCollection GetAllUsers()
        {
            return Membership.GetAllUsers();
        }

        public string GeneratePassword()
        {
            var alphaCaps = "QWERTYUIOPASDFGHJKLZXCVBNM";
            var alphaLow = "qwertyuiopasdfghjklzxcvbnm";
            var numerics = "1234567890";
            var special = "@#$";
            var allChars = alphaCaps + alphaLow + numerics + special;
            var r = new Random();
            var generatedPassword = "";
            for (int i = 0; i < MinPasswordLength - 1; i++)
            {
                double rand = r.NextDouble();
                if (i == 0)
                {
                    //First character is an upper case alphabet
                    generatedPassword += alphaCaps.ToCharArray()[(int)Math.Floor(rand * alphaCaps.Length)];
                    //Next one is numeric
                    rand = r.NextDouble();
                    generatedPassword += numerics.ToCharArray()[(int) Math.Floor(rand*numerics.Length)];
                }
                else
                {
                    generatedPassword += allChars.ToCharArray()[(int)Math.Floor(rand * allChars.Length)];
                }
            }
            return generatedPassword;
        }

        public int MinPasswordLength
        {
            get
            {
                return Membership.Provider.MinRequiredPasswordLength;
            }
        }

        public string AdminRole
        {
            get { return "admin"; }
        }

        public string MemberRole
        {
            get { return "member"; }
        }

        public string DelegateRole
        {
            get { return "delegate"; }
        }

        public bool Delete(string email)
        {
            return Membership.DeleteUser(email);
        }

        public bool IsAdmin()
        {
            return Roles.IsUserInRole(AdminRole);
        }

        public bool IsMember()
        {
            return Roles.IsUserInRole(MemberRole);
        }

        public bool IsDelegate()
        {
            return Roles.IsUserInRole(DelegateRole);
        }

        public bool ChangePassword(string email, string oldPassword, string newPassword)
        {
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
            if (String.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Value cannot be null or empty.", "oldPassword");
            if (String.IsNullOrEmpty(newPassword)) throw new ArgumentException("Value cannot be null or empty.", "newPassword");

            // The underlying ChangePassword() will throw an exception rather
            // than return false in certain failure scenarios.
            try
            {
                var currentUser = Membership.Provider.GetUser(email, true);
                return currentUser.ChangePassword(oldPassword, newPassword);
            }
            catch (ArgumentException)
            {
                return false;
            }
            catch (MembershipPasswordException)
            {
                return false;
            }
        }

        public string ResetPassword(string email)
        {
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
            var currentUser = Membership.Provider.GetUser(email, false);
            return currentUser.ResetPassword();
        }

        public bool CheckLocked(string email)
        {
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
            var currentUser = Membership.Provider.GetUser(email, false);
            if (currentUser == null) return false;
            if (!currentUser.IsLockedOut) return false;
            if (currentUser.LastLockoutDate.AddMinutes(30) < DateTime.Now)
            {
                currentUser.UnlockUser();
                return false;
            }
            return true;
        }

        public bool Unlock(string email)
        {
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
            var currentUser = Membership.Provider.GetUser(email, false);
            if (currentUser == null) return false;
            currentUser.UnlockUser();
            return true;
        }

        public void CheckRoles()
        {
            if (!Roles.RoleExists(MemberRole)) Roles.CreateRole(MemberRole);
            if (!Roles.RoleExists(AdminRole)) Roles.CreateRole(AdminRole);
            if (!Roles.RoleExists(DelegateRole)) Roles.CreateRole(DelegateRole);
        }
}

I'm not quite sure witch part you don't understand but let us know in details what are your problems and maybe we could help more! I think you need to get youre code building first.

And here's a good start for EF (so you can write youre custom profile/user in youre own database) : http://weblogs.asp.net/scottgu/archive/2010/08/03/using-ef-code-first-with-an-existing-database.aspx

倾城月光淡如水﹏ 2024-12-10 10:44:53

你不会把这种事情放在会员资格中。您将其放入配置文件或您自己的数据库中。

You don't put this sort of thing in Membership. You put it in Profiles, or your own DB.

热情消退 2024-12-10 10:44:53

非常感谢您的所有答案,所有这些都对我有帮助,我发现这个链接对我帮助很大,为您的答案添加信息,我想与社区分享,也许它可以帮助其他人:

< a href="http://www.java2s.com/Tutorial/ASP.NET/0420__Authentication-Authorization/UsingASPNETMembership.htm" rel="nofollow">http://www.java2s.com/Tutorial/ASP.NET/0420__Authentication-Authorization/UsingASPNETMembership.htm

thank you so much for all your answers, all of them were helpful for me, I found this link that helped me a lot, adding information to your answers, I would like to share with the community, maybe it can help someone else:

http://www.java2s.com/Tutorial/ASP.NET/0420__Authentication-Authorization/UsingASPNETMembership.htm

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文