0

I would like to control views in my action based on user roles. Roles are stored in database, I have overwritten my AuthorizeCore to return true or false based on who is authorized to access the view. I need to know the userRole in my controller.

How can I determine the role(s) for the current user?

[Authorize]
public ActionResult Index() {

if (userRole = "Admin") { return View("Admin");}
else {return View("Viewer");
}
John M. Wright
  • 4,477
  • 1
  • 43
  • 61
anand
  • 3
  • 4

1 Answers1

1

Assuming your controller extends System.Web.Mvc.Controller, then you can access the User property on the base class. This will give you an IPrincipal instance for the authenticated user, which includes .IsInRole(string role):

public ActionResult Index() {

    if (User.IsInRole("Admin")) { return View("Admin");}
    else {return View("Viewer");
}

Note: If your configured role provider doesn't automattically support using .IsInRole, you can implement your own db lookups using User.Identity.Name

John M. Wright
  • 4,477
  • 1
  • 43
  • 61
  • Thank John! Since the roles are in database, I need to assign(set) the roles before accessing them via User.IsInRole. I want to know how/where to assign the roles. – anand Dec 22 '17 at 21:09
  • @anand What role provider are you using? – John M. Wright Dec 22 '17 at 21:11
  • I don;t think I am using any role provider :( – anand Dec 22 '17 at 21:12
  • When you said "Roles are stored in database", what did you mean? – John M. Wright Dec 22 '17 at 21:13
  • all the users and roles are defined in the database. – anand Dec 22 '17 at 21:14
  • Ok, so you just need to query the database then. So you'd need a method that calls into your db with something like `select * from UserRoles where UserName = @UserName` (using the Contoller's `User.Identity.Name` for the username). – John M. Wright Dec 22 '17 at 21:15
  • I have a table, that assigns users to roles. User Role a Admin b Admin c Viewer d Viewer – anand Dec 22 '17 at 21:15
  • Right I am already doing that in AuthorizeCore. Can I set the role of the user in AuthorizeAttribute and then later access it in controller without querying the DB again. – anand Dec 22 '17 at 21:17
  • In that case, you _could_ add the user's roles to the passed-in `httpContext` object's `Session` key/value store in your `AuthorizeCore` method, then check the values from `this.HttpContext` in your controller. However, the preferred approach is to create a custom RoleProvider that implements `IsInRole`, which would also allow you to use the default `Authorize` attribute implementation. See https://stackoverflow.com/questions/18413036/override-the-user-isinrole-and-authorizeroles-admin-for-mvc4-application – John M. Wright Dec 22 '17 at 21:30
  • Thank you that resolved my issue. I did not know about the session object. – anand Dec 27 '17 at 17:28