What is a quick way I can add simple authentication to a few ASP.NET MVC routes, without implementing the whole Membership provider jazz?
I've created a demo website for my boss and one of 开发者_StackOverflow中文版the requirements is I need to add some simple authentication to his 3 admin views/routes.
What is the simplest, quickest way I can do this without implementing a whole membership provider? I honestly don't even care if the user/pass is hardcoded on the server side, I just need it so they can't access those 3 views without having authenticated in some way.
I would go this route.
Add this to your web.config (could omit the SHA1 and use a plain text password if you want):
<authentication mode="Forms">
<forms loginUrl="~/admin" timeout="2880">
<credentials passwordFormat="SHA1">
<user name="admin" password="4f3fc98f8d95160377022c5011d781b9188c7d46"/>
</credentials>
</forms>
</authentication>
Create a simple view for username and password and in the action method that receives the username and password go with this...
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOn(string username, string password)
{
if (FormsAuthentication.Authenticate(username, password))
{
FormsAuthentication.SetAuthCookie(username, false);
return RedirectToAction("Index", "Home");
}
else
{
ViewData["LastLoginFailed"] = true;
return View();
}
}
FormsAuthentication.Authenticate() automatically checks the username and password against the credentials node we created earlier. If it matches it creates your auth cookie with a "Remember Me" value of false and redirects you to the index view of your home controller. If it doesn't match it returns to the login page with ViewData["LastLoginFailed"] set to true so you can handle that in your view.
PS - Now that you have an easy way of authorizing don't forget to put the [Authorize] filter over the actions or controllers you want to protect.
easiest would be to select the menu [project] followed by [ASP.NET Configuration] in Visual Studio.
It'll set up a membership db for you. then add a couple of roles and users in the configuration manager that pops up.
that's it! Then simply decorate your actions/controllers with [Authorise] and check for some rights based on the user name. <= hard coded for the demo
精彩评论