ASP.NET - How to show all roles of the current logged in user (Windows authentication & impersonation)

Sounds quite easy and a lot of people have already blogged about

But if you get errors (YSOD*) like: 
“The Role Manager feature has not been enabled.”  or
“Method is only supported if the user name parameter matches the user name in the current Windows Identity.”
then the following might help you.

See following simple code example (don't blame me for using 1 label)

    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();

        sb.AppendLine(Environment.UserDomainName);
        sb.AppendLine("<br />");
        sb.AppendLine(Environment.UserName);
        sb.AppendLine("<br />");
        sb.AppendLine("---------");
        sb.AppendLine("<br />");

        foreach (string rolesForUser in Roles.GetRolesForUser(HttpContext.Current.User.Identity.Name))
        {
            sb.AppendLine(rolesForUser);
            sb.AppendLine("<br />");
        }

        Label1.Text = sb.ToString();

    }

The code is fine but you still get the error: "The Role Manager feature has not been enabled"

Reason is: We are using Windows authentication with impersonation and the role manager is not enabled and even not set to use the right one.

What is the role manager?
It manages roles and provides role based authentication (from http://msdn.microsoft.com/en-us/library/ms998314.aspx )

Which data store the role manager uses is defined in the web.config.
To access the data store we use a Data provider. This is the time when ”AspNetWindowsTokenRoleProvider” comes in to play.

 

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <system.web>
    <customErrors mode="Off"/>
    <authentication mode="Windows"/>
    <roleManager enabled="true"
             defaultProvider="AspNetWindowsTokenRoleProvider" /> 
    <identity impersonate="true"/>
    <authorization>
      <allow users="*"/>
    </authorization>
<!--  SNIP SNIP SNIP -->

Figure: Enable the role manager and ASP.NET is happy

Easy to use: We don’t need to setup a role store, because the Windows security system (AD) acts as role store for this provider

Read more about “How To: Use Role Manager in ASP.NET 2.0” on http://msdn.microsoft.com/en-us/library/ms998314.aspx

After this change you get a list of all roles of the current logged in user

MYDOMAIN 
pgfader 
--------- 
MYDOMAIN\Domain Users 
Everyone 
....
--- SNIP SNIP SNIP ---

 

PS
YSOD = Yellow screen of death

YSOD - Yellow Screen Of Death
Figure: Example of a YSOD

http://stackoverflow.com/questions/20198/how-does-the-asp-net-yellow-screen-of-death-display-code

http://stackoverflow.com/questions/878628/can-the-asp-net-yellow-screen-of-death-ysod-be-generated-on-demand-or-captured

Latest Posts

Popular Posts