You can use declaratively the PrincipalPermission attribute, in your code, when you want to validate the current user’s credentials. You can attach it to a given class or method and the CLR checks it automatically when the corresponding code runs. In this case time you cannot catch the exception within the function on which the attribute has been applied. You have to catch the exception in the function that actually calls this function. If you apply the PrincipalPermission attribute on an event procedure (such as Button_Click), you have to catch the exception in the global Application_Error event, which you can find in the Global.asax file.

By using a PrincipalPermission attribute, you can restrict access to a specific user or a specific role.  With the next code you can restrict access to specific page. Only users who belong to the server’s Administrators group can access it and if the user is not a member of this group, the ASP.NET runtime throws a security exception.  You have to catch the exception in the global error handler (Application_Error) because your code is not the caller of this web page.  Otherwise, ASP.NET would raise the exception and display the ASP.NET error page according to the web.config configuration:

 

Imports System.Security.Principal

‘…

‘…

<PrincipalPermission(SecurityAction.Demand, Role:=”BUILTIN\Administrators”)>

Public partial Class ImpersonateVB1

Inherits System.Web.UI.Page

‘….

End Class

 

With the next code you can restrict a particular method to a specific role and the caller of this method can catch the SecurityException with a try/catch block:

Imports System.Security.Principal

‘….

‘….

 <PrincipalPermission(SecurityAction.Demand, Role:=" THEDOMAIN\Logistic")> _
Shared Sub CheckAdministrator()
        Console.WriteLine("User is an administrator")
End Sub 'CheckAdministrator

 

 

Important Notes:

1. By using the PrincipalPermission attributes you can safeguard your code. You won’t use them to make decisions at runtime, but you might use them to ensure that even if web.config rules are modified  or circumvented, a basic level of security remains.

2. Declarative permissions are principally suited for fixed roles in your application that cannot be deleted. For example, an Administrators role is required in most applications and therefore cannot be deleted. So, you can secure functionality that should be accessible to only administrators with declarative permissions. Typical examples in Windows are all the built-in groups such as Administrators, Power Users, Backup Operators, and Users.