How to perform authorization checks for Role-Based authorization in ASP.NET in C#

When you enable the roles API, by following the approach described in the article How to use Roles API for Role-Based Authorization in ASP.NET, the RoleManagerModule automatically creates a RolePrincipal instance. This instance contains both the authenticated user’s identity and the roles of the user. The RolePrincipal is a custom implementation of IPrincipal, which is the base interface for all principal classes.  It as a result supports the default functionality, such as access to the authenticated identity and a method for verifying a role membership condition through the IsInRole() method. In addition, it provides a couple of additional properties for accessing more detailed information about the principal. You can use the properties in the following code to perform authorization checks by calling the IsInRole() method:

protected void Page_Load(object sender, EventArgs e)

{

if (User.Identity.IsAuthenticated)

{

RolePrincipal rp = (RolePrincipal)User;

StringBuilder RoleInfo = new StringBuilder();

RoleInfo.AppendFormat(“<h2>Welcome {0}</h2>”, rp.Identity.Name);

RoleInfo.AppendFormat(“<b>Provider:</b> {0}<BR>”, rp.ProviderName);

RoleInfo.AppendFormat(“<b>Version:</b> {0}<BR>”, rp.Version);

RoleInfo.AppendFormat(“<b>Expires at:</b> {0}<BR>”, rp.ExpireDate);

RoleInfo.Append(“<b>Roles:</b> “);

string[] roles = rp.GetRoles();

for (int i = 0; i < roles.Length; i++)

{

if (i > 0) RoleInfo.Append(“, “);

RoleInfo.Append(roles[i]);

}

LblRoleInfo.Text = RoleInfo.ToString();

}

}