The .NET Framework provides the WindowsPrincipal and GenericPrincipal classes, which provide basic role-checking functionality for Windows and non-Windows authentication mechanisms respectively. Both classes implement the IPrincipal interface. To be used for authorization, ASP.NET requires that these objects are stored in HttpContext.User. For Windows-based applications, they must be stored in Thread.CurrentPrincipal.
The functionality offered by these classes is sufficient for most application scenarios. Applications can explicitly call the IPrincipal.IsInRole method to perform programmatic role checks. The Demand method of the PrincipalPermission class, when used to demand that a caller belong to a particular role (either declaratively or imperatively) also results in a call to IPrincipal.IsInRole.
In some circumstances, you might need to develop your own principal implementations by creating a class that implements the IPrincipal interface. Any class that implements IPrincipal can be used for .NET authorization.
Reasons for implementing your own IPrincipal class include:
You want extended role checking functionality. You might want methods that allow you to check whether a particular user is a member of multiple roles. For example:
CustomPrincipal.IsInAllRoles( "Role1", "Role2", "Role3" ) CustomPrincipal.IsInAnyRole( "Role1", "Role2", "Role3" )
You want to implement an extra method or property that returns a list of roles in an array. For example:
string[] roles = CustomPrincipal.Roles;
You want your application to enforce role hierarchy logic. For example, a Senior Manager may be considered higher up in the hierarchy than a Manager. This could be tested using methods like the following.
CustomPrincipal.IsInHigherRole("Manager");
CustomPrincipal.IsInLowerRole("Manager");
You want to implement lazy initialization of the role lists. For example, you could dynamically load the role list only when a role check is requested.
This How To describes how to implement a custom IPrincipal class and use it for role-based authorization in an ASP.NET application that uses Forms authentication.