Ben Hickman's Blog

.NET Ramblings

Friday, February 07, 2003 - Posts

Custom roles for WindowsPrincipals in ASP.NET

I continue to be pleased with the many plug-points within ASP.NET. Recently, I had a student with an interesting ASP.NET security challenge. He wanted to use integrated windows authentication, but wanted to assign custom roles for the windows principals. He was building an intranet site. He needed a set of roles that didn't map to any existing Windows groups and he couldn't get the network admins to add them (and keep them updated). 

It turns out this is quite easy with ASP.NET. First, create a new class to hold the roles (thankfully, WindowsPrincipal isn't sealed!):

using System.Collections;
using System.Security.Principal;

public class CustomPrincipal : WindowsPrincipal
{
    private ArrayList m_Roles;

    public CustomPrincipal(WindowsIdentity identity): base(identity)
    {
        m_Roles = new ArrayList?();
    }

    public override bool IsInRole(string role)
    {
        // May or may not make sense to check
        // WindowsPrincipal role if membership fails
        // for the local list.
        if (m_Roles.Contains(role))
            return true;
        else
            return base.IsInRole(role);
    }

    public void AddRole(string role)
    {
        m_Roles.Add(role);
    }
}

Now, add the following code to Global.asax.cs to hook into the Windows authentication process in ASP.NET and setup the new CustomPrincipal and its roles:

protected void WindowsAuthentication_OnAuthenticate(object sender,
    WindowsAuthenticationEventArgs e)
{
    if (e.Identity != null && e.Identity.IsAuthenticated)
    {
        CustomPrincipal p = new CustomPrincipal((WindowsIdentity)e.Identity);

        //
        // Add the appropriate roles, e.g. read
        // them out of a database.
        p.AddRole("CustomRole");
        HttpContext.Current.User = p;
    }
}

Then, just use the normal ASP.NET authorization services. You can write code that uses Page.User.IsInRole() or using Web.config, e.g.:

<authentication mode="Windows" />
<identity impersonate="true" >
<authorization>
    <allow roles="BUILTIN\Administrators" />
    <allow roles="CustomRole" />
    <deny users="*" />
</authorization>

And Begin
Hello weblog
More Posts