2

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.

Scopperloit
  • 920
  • 12
  • 23
  • Seems Ok. Will be very limited and if you do it in multiple places you will have high code maintenance. Consider creating a constant collection for the role names so you can at least rename them or change them easily in the future if need be:) – Ben Pretorius Feb 19 '14 at 08:19

1 Answers1

2

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();
}
Jelle Oosterbosch
  • 1,731
  • 15
  • 17