Question

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.

Was it helpful?

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top