ASP.NET MVC Authentication using AccountController

The AccountController class is a controller for user authentication which is included in a default MVC project created with Visual Studio. Prior to using this controller, you will need to modify it so that it no longer refers to the HomeController which you most likely will remove. To do this, replace each of these instances:

return RedirectToAction("Index", "Home");

so they are as below:

return RedirectToAction("Index", "Products");

This will cause the authentication controller to redirect a user to the products controller once an authentication action ends. The default ASP.NET MVC master page has links for a  user to log in/out and register. The MVC Authorize filter facilitates control over which users may access the controller methods. Below is an example of the Authorize filter being  applied to the Delete method in the products controller class:

[Authorize]
public ActionResult Delete(int id) {
NorthwindEntities dbObj = new NorthwindEntities();
var data = dbObj.Products.Where(e => e.ProductID == id).Select(e => e).Single();
return View(data);
}

If a user clicks a delete link to delete a record of a product, the MVC framework is then checked. If the user is currently logged in, the action will proceed.. If the user has not logged in they will then be requested to provide their username and password credentials or else to create a new account. This can be made even more restrictive by specifying user names as part of the filter. Below is an example of the Authorize filter applied so the Delete method is only available to Mike Smith:

[Authorize(Users="Mike Smith")]
public ActionResult Delete(int id) {

Now only Mike Smith can perform the delete actions, all other users will be asked for their credentials. The MVC Authorize filter can even be applied to the whole controller class. Below is an example of the Authorize filter being applied to the ProductsController class, so that only authenticated users can access controller actions:

[HandleError(Order=2)]
[Authorize]
public class ProductsController : Controller {

The Authorize filter has an Order property which works just as the HandleError Order property. If the  Authorize filter is applied for the whole controller level and for a specific action method, the controller-wide setting will always have precedence unless the Order property is used.