-1

if I'm using AuthorizeAttribute on controller level to deny/allow access to certain resources how can I further down in block of code determine logged users roles, like I can using User.Identity.Name determine logged user name.

[Authorize(Roles="Admin, GroupA, GroupB")]
public class MyController : Controller
{
   // switch user roles here       
}
user1765862
  • 13,635
  • 28
  • 115
  • 220

2 Answers2

1

You can use Roles.GetRolesForUser(User.Identity.Name)

Ken Tucker
  • 4,126
  • 1
  • 18
  • 24
  • Roles.GetRolesForUser(User.Identity.Name) will throw an exception Object reference not set to an instance of an object with yellow screen of death. See my implementation below – Julius Depulla Nov 01 '15 at 21:14
0
        [Authorize(Roles="Admin, GroupA, GroupB")]
        public class MyController : Controller
        {
            public async Task<ActionResult> AddOrder(Order order)
            {
                 var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

                 //returns all roles for the user Id

                  var roles = await userManager.GetRolesAsync(User.Identity.GetUserId());

                  //Additionally you may want to check the role exist
                  var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext());
                  var roleManager = new RoleManager<IdentityRole>(roleStore);

                  bool isRoleExist = await roleManager.RoleExistsAsync("Admin");          
                  return View();
            }
        }
Julius Depulla
  • 1,493
  • 1
  • 12
  • 27