We think it's better to loop through the Roles in the principal object.
However, to do this, you have to create your own custom implementation of
IPrincipal, which is actually not that hard to do. We've included an
implementation below (sorry, C# code):
using System;
using System.Security.Principal;
namespace Ng.Auth
{
/// <summary>
/// Summary description for CustomPrincipal.
/// </summary>
public class CustomPrincipal : IPrincipal
{
private IIdentity _objIdentity;
private string [] _strRoles;
public CustomPrincipal(IIdentity objIdentity, string[] strRoles)
{
_objIdentity = objIdentity;
_strRoles = new string[strRoles.Length];
strRoles.CopyTo(_strRoles, 0);
Array.Sort(_strRoles);
}
public bool IsInRole(string strRole)
{
return Array.BinarySearch( _strRoles, strRole ) >=0 ? true : false;
}
public IIdentity Identity
{
get
{
return _objIdentity;
}
}
public string[] Roles
{
get
{
return _strRoles;
}
}
}
}
At this point it has become very easy to loop through all roles, like this:
// First do this:
string[] strOrgRoles = { "admin", "user", "teamadmin" };
HttpContext.Current.User = new CustomPrincipal(User.Identity, strOrgRoles);
// At a later time do this:
CustomPrincipal objPrincipal = (CustomPrincipal) HttpContext.Current.User;
foreach ( string strRole in objPrincipal.Roles )
{
Response.Write(strRole + "<br />");
}
You're probably better off using this approach instead of querying the
database. Something we recently came across, is somewhat related to your
question. It involves querying all roles of the windows identity. The code is
based on an example from Joe Kaplan in VB.NET. It might also be useful. It
uses reflection to get to the roles.
WindowsIdentity objCurrentIdentity = WindowsIdentity.GetCurrent();
Type objIdentityType = typeof(WindowsIdentity);
object objRoles = objIdentityType.InvokeMember("_GetRoles",
BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.NonPublic,
null, objCurrentIdentity, new object[] { objCurrentIdentity.Token }, null);
string[] strRoles = (string[]) objRoles;
Kind regards,
Nikander & Margriet Bruggeman
:
Following
http://aspnet.4guysfromrolla.com/articles/082703-1.aspx I've
set up roles authentication for my web application.
User's roles are registered by:
HttpContext.Current.User = _
New GenericPrincipal(User.Identity, roleListArray)
I'd like to enter a user's roles into a listbox for viewing.
Must I loop all roles from datastore and check if user has role, or
can I somehow loop the specific user's roles (something like for each
role in user.roles)?
Mort