powered by Slim Framework
enhanced by Nesbot.com

MVC3: Login System with the AuthorizeAttribute

Published on Aug 23, 2011 by Jamie Munro

If you are creating your first website with MVC3 and it requires users to register and login, the AuthorizeAttribute and a built-in Internet Application template will get you started.



Assumptions



MVC3 could not make this process any simpler. When you create a new MVC3 application, select the Internet Application template.

Done! You now have a fully functional registration and login process. There is even a Remember Me checkbox to prevent users from having to re-type their login information on each visit.

Now you need to add a new action or even a new controller and you want to ensure the user is logged in before displaying the content. This is done by adding the following line of code above your function:


[Authorize]


If you open the AccountController.cs file in the Controllers folder, you will see an example of this with the ChangePassword function:


//
// GET: /Account/ChangePassword
[Authorize]
public ActionResult ChangePassword()
{
return View();
}


To allow for further control over who can access a view, you can enable access to specific groups or specific users. This is done through the Roles and Users properties, respectively.


//
// GET: /Account/ManageUsers
[Authorize(Roles = "Admin")]
public ActionResult ManageUsers()
{
return View();
}


OR


//
// GET: /Account/ManageUsers
[Authorize(Users = "Jamie,Shannon")]
public ActionResult ManageUsers()
{
return View();
}


If you are looking to get more adventurous you can override the default AuthorizeAttribute and add in your own authentication process perhaps Facebook Connect or some other third party login? I think I will leave that for an article unto itself!

Summary


The AuthorizeAttribute is extremely useful because it is independent of your authentication mode. Also, almost more importantly; however, requires a bit of extra typing, it is added to each action that requires authentication. No complex setup to say add it to these three functions, but allow this one, etc.

Tags: ASP.NET | mvc3

<- CakePHP: Scaffolding a new database table  Home CakePHP: Login System using the Authentication Component -> 
blog comments powered by Disqus