Help implementing simple / custom MembershipProvid

2019-06-12 05:35发布

问题:

I have been follow Steve Sandersons MVC2 book and have implemented a simple / custom MembershipProvider. You will not that a valid user has been hardcoded. My question is how do I get this to validate against my "Profiles" SQLServer table?

PS - I am using EF 4.1 Code First

Please see below:

public class Profile
{
    [Key]
    public int UserId { get; set; }

    [Required]
    public string UserName { get; set; }

    [Required]
    public string Password { get; set; }
}

public class SimpleMembershipProvider : MembershipProvider
{
    private static List<Profile> Members = new List<Profile>
    {
        new Profile { UserId = 1, UserName = "admin", Password = "qwerty123" }
    };

    public override bool ValidateUser(string username, string password)
    {
        return Members.Exists(m => (m.UserName == username) && (m.Password == password));
    }

回答1:

You need to make your User security data tables. Here's 2 tables for start:

UserNames table:

UserID    UserName
1         alex
2         john

UserSecurityDetails table:

UserID    Password
1         qwerty123
2         password1

You then want to make your models (making a UserObjectContext) around those tables. There should be an association between the userIDs.

Then you can use those models in you validate method. Something like:

public override bool ValidateUser(string username, string password)
{
    using(var context = new UserObjectContext())
    {
        return context.UserNames.Any(u => u.UserName == username && u.UserSecurityDetails.Password == password);
    }
}