Config-based authentication in ASP.NET MVC4

2019-08-19 19:36发布

问题:

I have an ASP.NET MVC4 web page that is, for the most part, accessed without authentication. There is a single page that I want to protect for admin-only access (ELMAH's error log, specifically). Since I only require a single admin login, I'd like to avoid the complexity of maintaining a user/password database.

I've done some research, and I've found that previous versions of ASP.NET provide the ability to use Forms Authentication with a password encrypted in the web.config:

<forms loginUrl="Admin" name=".ASPXFORMSAUTH">
  <credentials passwordFormat="SHA1">
    <user name="admin" password="encryptedPassword" />
  </credentials>
</forms>

Then, the authentication controller uses FormsAuthentication.Authenticate and FormsAuthentication.RedirectFromLoginPage to validate entered credentials. However, I'm hesitant to use this solution because:

  1. The FormsAuthentication.Authenticate API is now obsolete.
  2. FormsAuthentication.RedirectFromLoginPage will redirect the user directly, rather than returning a RedirectResult. This doesn't follow the MVC controller pipeline, and so things like unit testing would be more difficult.

Looking through MSDN samples and the default template, it appears that WebMatrix's WebSecurity.Login API is the new standard for doing Forms Authentication in MVC applications. But, I haven't found a way to use a local (i.e. config-based) authentication provider.

Is there a recommended way to do local authentication, or is this considered a bad practice? What's the simplest method to provide admin authentication without taking on external dependencies?

回答1:

WebSecurity.Login is not "the new standard" for authentication. It's more like the new "newbie friendly standard". WebSecurity only really supports SimpleMembership, and that is really simply designed for simple applications.

FormsAuthentication.Authenticate has not been a good choice for a long time, so the fact that it's now officially deprecated is not a big deal.

You should probably be using Membership anyways, and use Membership.ValidateUser to validate credentials. Or, use something like Windows Identity Foundation.