ASP.NET MVC > Authentication and Authorization

Implementing authorization in ASP.NET MVC

How to implement authorization in controller action method of ASP.NET MVC?


To perform authorization, we can use Authorize attribute in the action method of the controller. We can authorize users based on their username or role defined in the database.

Authorizing based on username

CONTROLLER CODE

[Authorize(Users = "Ram")] // more users can be separated by comma
public ActionResult RamUserOnly()
{
    return View();
}

Above action method (corresponding view) will be accessible to only user whose username is “Ram” ie. when Ram is logged in then only RamUserOnly action method will be accessible, other users will get redirected to /Account/Login page as implemented in ASP.NET Identity provider.

Authorizing based on role

CONTROLLER CODE

[Authorize(Roles = "Admin")] // more roles can be separated by comma
public ActionResult AdminOnly()
{
    return View();
}

Above method will be accessible only to those user whose role is “Admin” defined in the AspNetUserRoles database table.

CONTROLLER CODE

[Authorize(Roles = "Admin, SuperAdmin")] // can be separated by comma
  public ActionResult AdminOnly()
  {
      return View();
  }

Above method will be accessible only to those user whose role is “Admin” or “SuperAdmin” defined in the AspNetUserRoles database table.

By default ASP.NET MVC default project doesn't provide user interface (controller and views) to create, map roles, read this article to work with Roles in ASP.NET MVC 5.

 Views: 27229 | Post Order: 78



Write for us






Hosting Recommendations