Overview Security Classes in VB.NET: Part 3
In this article I will explain you about Security Classes in VB.NET.
See Part 1, Part 2
The example22.17 given below illustrates a typical use of the Assert method. First, file I/O permission is demanded. Then the Assert method is called to affirm permission to unmanaged code. As a result, no more stack walk-ups are performed until processing of the unmanaged code is complete.
Listing 22.17: Assert Example
Try
Dim p1 As New FileIOPermission(FileIOPermissionAccess.Read, "C:\dir1\")
filePerm.Demand()
Dim unmanagedPerm As New SecurityPermission(SecurityPermissionFlags.UnmanagedCode)
' call unmanaged code
unmanagedPerm.Assert()
' demand for file I/O permission failed.
Catch
End Try
Listing 22.18 uses the Demand and Assert methods together for performance tuning. First, you demand an environment variable for read permission. Then you assert that need and execute nonrisky code in terms of that environment permission.
Listing 22.18: Demand and Assert Example
' demand and assert together
Try
Dim envPerm As New EnvironmentPermission(EnvironmentPermissionAccess.Read, "TEMP")
' Demand it once to see if it has been granted.
envPerm.Demand()
' Assert the permission to stop the stack walk here.
envPerm.Assert()
' code that reads TEMP environment variable
For i As Integer = 0 To 99
Next
' The demand failed.
Catch
End Try
SecurityAction Enumeration
SecurityAction is an enumeration that encompasses the following elements:
-
LinkDemand
-
InheritanceDemand
-
Demand
-
Assert
-
Deny
-
PermitOnly
-
RequestMinimum
-
RequestOptional
-
RequestRefuse
SecurityPermissionFlag Enumeration
The SecurityPermissionFlag enumeration helps to specify access flags for the security permission object. The SecurityPermission class uses this enumeration. Many of these flags are powerful and should be granted only to highly trusted code.
The enumeration contains the following elements:
-
AllFlags
-
Assertion
-
ControlAppDomain
-
ControlDomainPolicy
-
ControlEvidence
-
ControlPolicy
-
ControlPrincipal
-
ControlThread
-
Execution
-
Infrastructure
-
NoFlags
-
RemotingConfiguration
-
SerializationFormatter
-
SkipVerification
-
UnmanagedCode
Listing 22.19 shows how to use the SecurityPermissionFlag enumeration to request minimum security in the class attributes. This causes security verification to be skipped during JIT compilation.
Listing 22.19: SecurityPermissionFlag
// SecurityPermissionFlag
<SecurityPermissionAttribute(SecurityAction.RequestMinimum,
Flags:=SecurityPermissionFlag.SkipVerification)> _
Public Class MySecureClass
Shared Sub DenyAllSecurityPermissions()
// code here
End Sub
End Class
Conclusion
Hope this article would have helped you in understanding Security Classes in VB.NET.