Creating Custom Principal Class

For creating a Custom Principal class, implement it based on the

ITPro Today

April 5, 2005

6 Min Read
ITPro Today logo in a gray background | ITPro Today

For creating a Custom Principal class, implement it based on the IPrincipal. There are some interesting

benefits by overriding the IPrincipal Interface. Check out the Benefits mentioned below.

 

  1. Adding a “Roles” property that returns an array of strings containing the roles the user is a member of.

 

  1. Adding “IsHigherThan” or “IsLowerThan” methods to enable Hierarchical group membership.

C# Code Sample

 

Using System;

Using System.Security.Principal;

 

namespace CustomRoleBasedSecurity

{

 

Public class CustomPrincipal : IPrinicpal

{

     //Implementing the Private Variables for the Standard Properties

 

Private IIdentity _identity;

       Private string [] _roles;

      

     //Allow caller to create the Object and Specify all properties

     Public CustomPrincipal (IIdentity identify, string [] roles)

{

 

 _identify = identity;

 _roles    = new string [roles. Length];

 roles.CopyTo(_roles,0);

 Array.Sort(_roles);

}                         

 

//Implement Public read-only Interfaces for Standard Properties

Public bool IsInRole (string role)

{

 

  return Array.BinarySearch(_roles, role) > = 0 ? true :false;

 

}

 

Public IIdentity Identity

{

 

 Get

 { return_identity;}

}

}

}

VB.NET Code Sample

 

Imports System;

Imports System.Security.Principal;

 

Public Class CustomPrinicipal Implements IPrincipal

 

 ‘Implement Private variables for Standard Properties

  Private _identity as IIdentity

  Private _roles as String()

 

 ‘Allowing the caller to create the Object and Specify all Properties

 

Public Sub New (ByVal Identity As IIdentity, ByVal roles as String())

_identity = identity

roles.CopyTo(_roles, 0)

Array.Sort(_roles)

End Sub

 

‘Implement Public read-only Interfaces for Standard Properties

Public Function IsinRole(ByVal role as String) As Boolean

       Implements Iprincipal.IsInrole

       Return False

End Function

 

Public ReadOnly property Identity() as IIdentity

       Implements IPrincipal.Identity

       Get

              Return_identity

       End Get

End Property

End Class      

 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like