1

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!

Community
  • 1
  • 1
Rubia Gardini
  • 815
  • 5
  • 16
  • 30

4 Answers4

2

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.

Brice
  • 21
  • 1
  • Thank you Brice, useful information. I'm still wondering how to implement classes to register a new user in the aspnet tables, retrieve any ID and add other details to other table, still confused, but your information was really helpful. – Rubia Gardini Sep 07 '11 at 19:39
1

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

VinnyG
  • 6,883
  • 7
  • 58
  • 76
  • Hi VinnyG, your information is very useful, thank you for the codes and explanation, now I need realize how to make an anonymous user to register in my website via form, and use in the registration controller the membership classes. Ps: I loved Scottgu's link ^^ – Rubia Gardini Sep 07 '11 at 23:51
0

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

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
  • thank you, as you see I'm totally beginner to that, I'm already 2 days looking for information, those classes are totally new for me, I really appreciate community help to understand that, and a guide how to procceed now – Rubia Gardini Sep 07 '11 at 19:29
0

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

Community
  • 1
  • 1
Rubia Gardini
  • 815
  • 5
  • 16
  • 30