Search code examples
asp.net-mvc-4simplemembershipcustom-membershipprovider

Specifying password field to SimpleMembershipProvider


I'm implementing SimpleMembershipProvider in a small MVC4 project, and I can already initialize the database connection using a customer-provided DB with the user and role tables already specified (those are called sp_person and sp_role).

The problem is, when I try to log in, the MVC app rejects my password with the typical "incorrect password" error message though I already know that it's the correct password. I suspect the problem is that SimpleMembershipProvider does not know where do I store the password (it's in the sp_person table, in the "ecampus_password" field) and that's why authentication fails.

How can I tell SimpleMembershipProvider where to look for the stored password?

Thanks in advance,

Léster


Solution

  • Nevermind, I found that SimpleMembershipProvider is not the solution. In this case, I'm supposed to implement a custom provider.

    Steps as follows:

    • Add an Entity Data Model to the project that consumes only the tables related to the auth scheme (in my case, importing only sp_person and sp_role).
    • Add System.Web.ApplicationServices as a reference to the project.
    • Add a new class to the project, point to System.Web.Security in a using statement and make the class inherit from MembershipProvider. MembershipProvider is an abstract class, so implement it when asked.
    • Add an object to the class of the type Entity Framework created for you when you added the data model (it's usually called <CONNECTION_NAME>Entities, you can change that when creating the model). Something like this:

      public class MyMembershipProvider : MembershipProvider
      {
          private MYCONNECTIONEntities db = new MYCONNECTIONEntities ();
      }
      
    • Strictly, you might have to implement every property and method in the class, but for auth, you must implement ValidateUser(). Simply using a LINQ query to retrieve the user from your data model will do. Here's mine:

      var list = from u in db.st_person
                 where u.ecampus_login == username
                 && u.person_password == password
                 select u;
      return list.Count() > 0;
      
    • In web.config, under the <authentication> element, add the new provider like this:

      <membership defaultProvider="MyMembershipProvider">
        <providers>
          <clear />
          <add name="MyMembershipProvider" type="PROJECT_NAME.MyMembershipProvider"/>
        </providers>
      </membership>
      
    • Compile and test.