A way to avoid deriving from the provider classes

2019-07-18 23:40发布

问题:

Looking for the best practice for authentication in MVC I unfortunately didn't find the clear answer to my question. Thinking of the problem I tried to imagine some principles that could be useful in my design. Well,

  1. I would like to use a base AccountController class
  2. I want to place all the tables such as "Users", Roles, Rights etc into my own database. But I wouldn't like to implement the standard aspnetdb design (which can be easy got by using aspnet_regsql)

So the main question is can I do this without deriving abstract classes like MembershipProvider, RoleProvider etc? What I would prefer not to do is implement all the abstract methods from these classes.

The second question is still about the best practice for authentication e.g. for the small projects, for the large ones?

回答1:

You can actually get most of the basic required functionality working without implementing every method in MembershipProvider and RoleProvider

Just use throw new NotImplementedException(); as the body of properties/methods you aren't going to use.

My custom membership provider just provides real implementations for

  • bool ChangePassword(string username, string oldPassword, string newPassword)
  • MembershipUser GetUser(string username, bool userIsOnline)
  • bool ValidateUser(string username, string password)

and throw new NotImplementedException(); for the rest.

Likewise, my custom role provider just implements

  • string[] GetRolesForUser(string username)

With this I can use the basic built-in authorization and authentication without to much effort.



回答2:

From the MembershipProvider documentation on MSDN:

When implementing a custom membership provider, you are required to inherit the MembershipProvider abstract class.

There are two primary reasons for creating a custom membership provider.

  • You need to store membership information in a data source that is not supported by the membership providers included with the .NET Framework, such as a FoxPro database, an Oracle database, or other data source.

  • You need to manage membership information using a database schema that is different from the database schema used by the providers that ship with the .NET Framework. A common example of this would be membership data that already exists in a SQL Server database for a company or Web site.

Emphasis mine. When you override the methods, you are in control of how, when, and where all of the membership information is derived. Your tables, your way.

Note that the MembershipProvider class is abstract. It doesn't do anything on its own. The class that uses the schema you're referring to is an entirely different class.