12

I'm trying to add Roles authentication to an Action in a Controller in an ASP.NET MVC application. The code looks something like this:

[Authorize(Roles = "SomeRoleName")]
public ActionResult Index()
{
    bool inRole = User.IsInRole("Admin");

If I remove the Authorize attribute and put a breakpoint on the last line in that code sample, is there a way that I can inspect the objects and find out what roles are available?

e.g. I call User.IsInRole("Admin) in the Immediate window and it will give me a true/false value. How can I access the collection of roles available?

Guy
  • 65,082
  • 97
  • 254
  • 325
  • Can you clarify your question as to whether you're looking for the roles assigned to the current user or all possible roles that a user could belong to? – Kevin Pullin May 29 '09 at 00:53

4 Answers4

16

If you don't need to do this programatically, but you are trying to determine the correct Windows Groups/Roles that need to be specified, you can use this from the command line:

C:\> net group /domain  (lists all Roles in the domain)
C:\> net user <username> /domain (lists info, including roles for a user)

Otherwise you will need to query the LDAP part of Active Directory, or use something under DirectoryServices.

Take a look at these websites to access Active Directory via C#:

Astra
  • 10,735
  • 3
  • 37
  • 41
  • 1
    Well, the howto link takes me to 'Chinese dates' now. – Jake Gaston Dec 07 '16 at 18:07
  • In case someone else wanders in here. The link for "Howto: (Almost) Everything In Active Directory via C# - Codeproject" is: https://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C – allen.mn Aug 29 '17 at 18:38
8

Add this to your web.config under system.web:

<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider"/>

Then you can use:

string[] arr = Roles.GetRolesForUser(User.Identity.Name);

or:

string[] arr = Roles.GetRolesForUser();

enter image description here

Iman
  • 17,932
  • 6
  • 80
  • 90
beatoss
  • 395
  • 6
  • 13
  • 1
    thanks, this gives all local and domain roles very fast , for example BUILTIN\\Administrators group too – Iman Nov 05 '16 at 14:13
3

You can use the various methods on the RoleProvider class in System.Web.Security.Roles.Provider.

See this for more: Role Provider

Kevin Pullin
  • 13,122
  • 3
  • 24
  • 33
1

I'm guessing you aren't using a role provider here, but falling back on the underlying functionality of WindowsPrincipal where the roles map to the user's groups. Anyhow, I don't think one can do more than enumerate the windows groups available on that machine/in that domain. Not sure if this helps, but that's all I can say without having an idea of what you are trying to do with said roles list.

Wyatt Barnett
  • 15,573
  • 3
  • 34
  • 53