Search code examples
asp.netasp.net-mvcauthorizationasp.net-mvc-5asp.net-roles

Individual page authorization based on roles in ASP.NET MVC 5


I am pretty new to ASP.NET MVC, and I'm trying to build a web-site that uses MVC 5's built-in authorization methods.

Here's what I've done so far:

  1. Created a number of users in the AspNetUsers table.
  2. Created a number of roles in the AspNetRoles table.
  3. Assigned roles to users via the AspNetUserRoles table by connecting RoleID and UserID.

Now, to set up a single page to only show certain content to users with the admin-role, and hide it otherwise, I've done this:

@if(User.IsInRole("Admin")) 
{
    <p>You are logged in as an admin.</p>   
} else
{
    <p>You are not logged in as an admin.</p>
};

Is this OK to do, or is this bad? I've played around with it for quite some time, and it works as expected (as far as I can tell).

I know I can create CustomAuthorizationAttributes and assign these to the ActionMethods in the Controller, but I'm not 100 % comfortable with the syntax on this.


Solution

  • If you are happy with the syntax, this is fine.

    But you cannot forget to protect the view itself with the Authorize attribute. You can use the default as following

    [Authorize(Roles = "Admin")]
    public ActionResult Register()
    {
    ...
    return View();
    }