简体   繁体   中英

Basic Login / Authorization in MVC4

I have two Controllers in my MVC4 application that I want to require users to be logged into to access; an 'admin' area of sorts.

I have a database linked class that handles authentication for me in C#, meaning I can do something like this:

LoginUtility lu = new LoginUtility();
if(lu.Login("username", "password") == true){
   // User is genuine
} else {
   // Login failed
}

I want to hook this up to MVC4 so I can apply the [Authorize] attribute to those two Controllers.

You should use a basic Web Application Template, it gives you controllers to edit users and use authentication. Then, you will be able to allow certain controllers, or certain action of controllers. For a controller, you just have to put [Authorize(Roles = "Admin")] tag just before the definition of the controller to just allow this action to Admin Roles.

I have found doing custom login logic quite the pain. What you need to do is extend AuthorizeAttribute so you can use it on your controllers/actions, and override AuthorizeCore . If you need custom logic to extract the username and password from the request, you can do that through setting the User property on HttpContext in an OnAuthorization override.

In your web.config add :

<authentication mode="Forms">
  <forms loginUrl="login.aspx" />
</authentication>

And in your controller :

LoginUtility lu = new LoginUtility();
if(lu.Login("username", "password") == true){
 FormsAuthentication.SetAuthCookie(...);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM