Visual Guard Class Library Documentation

How to apply security in your application

There are two ways to apply security in an application with Visual Guard: execute security actions or test permissions in the code of your application.

The first way is fully dynamic and separates the implementation of the security in your application from the rest of your code but has some limitations when you need to apply security on object loaded dynamically or when the permission are tightly integrated with the data of the application .

The second way allows you to tightly integrate the security in your application but needs to modify the code of your application and to deploy your application each time the security implementation needs to be modified.

Using Security Actions

Security actions are defined in the Visual Guard console and attached to a specific permission. When the permission is granted to a user, Visual Guard will execute the security action in your application. There are 2 types of security actions:

Properties Action

These security actions will modify the value of property of components of the application. For example, Visual Guard can set the property 'Enabled' of the button 'OK' to false or can set the property 'Filter' of a Dataview containing the customer list to 'Country = 'USA''.

These actions can be executed when Visual Guard loads the security for the object or when an event of the object is raised (see: How Visual Guard secures an application). For example, you can execute an action that will disable the button 'OK' each time the event 'EnabledChanged' of the button 'OK' is raised. In this case the button will be always disabled.

You can also define a condition for a security action. Visual Guard will evaluate the condition just before executing an action. When the condition is false, the action is not executed. For example, you want to disallow to modify a sales order in a form the when the user is not the creator of the sales order. In this case, you can define a Property 'IsCreator' on your form (this property must be a 'public' property). This property will indicate when the current user is he creator of the Sales Order. In your security action you will add a condition that will check this property before disabling the button 'Save' and setting fields in ReadOnly mode.

You can also use permission arguments to change the value of a property. For example, you want to display only sales orders created by employees based in a country. You should create a permission with an argument 'Country'. This argument will contain the Country code used to filter the list. After, you should add a security action to this permission. This action will change the property 'Filter' of the Dataview containing the list of Sales orders. The value will not be a predefined value but a value based on a Visual Guard expression. The expression will be:

#CurrentValue + ' And Country = '''+ #Permission['Country'] + ''''               

Visual Guard will evaluate the expression at runtime and replace the current value of Filter property by the value of the expression.

When an object is dynamically created (like Template in WebForm application), Visual Guard cannot see this object and you cannot add an action on this objects. In this case you can add a public property on your target object and set this property. For example, the column 'Salary' of a GridView in WebFrom requires to be hided by a permission. The 'Salary' column is not visible in the Visual Guard console. You have to add the property 'HideSalary' on your WebForm and test the value in your program to determines whether the column is visible.

public bool HideSalary
        return hideSalary;
        hideSalary = value; 
        EmployeeDataList.Columns[5].Visible = value; 

Once the property is added, you can add a security action that will set this property when needed.

Script Action

This type of action enables you to execute a script defined in the Visual Guard console when a permission is granted to a user. The scripts will be dynamically compiled at runtime when the security is loaded for a user and will be executed in the domain of the application. You can use in these scripts the class of your application like in the code of your application.

The following example shows how to use the information available from the script.

Option Explicit On

Imports Novalys.VisualGuard.NorthwindSample
Imports Novalys.VisualGuard.Security
Imports Novalys.VisualGuard.Security.Action
Imports System
Imports System.Collections
Imports System.Windows.Forms
Imports System.Text

Namespace Novalys.VisualGuard.DynamicScript
Public Class Cdff07f9054f2411bac2d424a4346dc27
Inherits Novalys.VisualGuard.Security.Action.VGDynamicScript
Public Overrides Sub Execute(ByVal target As Object, ByVal permission As VGIPermission, ByVal eventArgs() As Object)
        ' All script actions can be see in the debugger
        ' If the current application is in debug mode, signals a breakpoint to the debugger

        ' This parameter contains the object for which the action is executed
        Dim main as MDIForm = CType(target, MDIForm)
= main.Text + " ********"
        ' Information about the current permission and its attributes
        Dim sb As New StringBuilder
"Current Permission : {0} (id={1})", permission.Name, permission.Id)
" * Value of the permission attribute 'Attribute1': {0}", permission.Item("Attribute1"))
" * Value of the permission attribute 'Attribute2': {0}", permission.Item("Attribute2"))

        ' Information about the arguments of the event for which the action is executed.
        ' For example for a click event:
        '    * the first element in the array is the sender.
        '      * the second is the EventArgs.
        If eventArgs.Length > 0 Then
"Event Information")
For Each arg As Object In eventArgs
" * {0}", arg.GetType().ToString())
"The event does not have any arguments")
End If

        ' Information about the current principal
        sb.AppendFormat("Current User: {0}", VGSecurityManager.Principal.Identity.Name)
For Each role As VGGrantedRole In VGSecurityManager.Principal.Roles
"{0}, ", role.Name)
End Sub
End Class
End Namespace

Testing permissions in your application

In some cases, it is not possible to use security actions in order to adapt the application to the permission granted to the user. For example, it is not possible to Visual Guard to apply security action on object created dynamically in your application. It is also difficult to apply security actions depending on data defined in the application. In this case, you will need to check in your application when a permission or role is granted to the current user.

The property VGSecurityManager.Principal allows you to get information about the current user. You can you use the method VGSecurityManager.Principal.HasPermission to check whether a permission is granted to this user and the method VGSecurityManager.Principal.IsInRole to determine whether this user belongs to a role.

This example shows how to determine whether the permission 'Display only information on a country' is granted to the current user and how to get the value of the argument 'Country'.

If Not VGSecurityManager.Principal.HasPermission("Display only information on a country") Then
    MessageBox.Show("The current user can see all countries"
    Dim myPerm As  VGSecurityManager.Principal.GetPermission("Display only information on a country")
    Dim myValue As String = CType(myPerm("Country"), String)
    MessageBox.Show(String.Format("The current user can see only information about the country '{0}'", myValue))
End If

When the value of a permission argument can only be resolved at runtime, you can change the value by using the property VGIPermissionAttribute.Value.

Using VGPrincipalPermission and Code Access Security

Visual Guard enables you to use the code access security to restrict the access to a method or a class. For example, the code below prevents the "MethodWithRestrictedAccess' method from being invoked by users that is not an administrator and do not have the '\Employees\Allows to edit employees' permission

<VGPrincipalPermission(SecurityAction.Demand, Name="Administrator",Type=VGPermissionType.Role]> _
<VGPrincipalPermission(SecurityAction.Demand, Name="\Employees\Allows to edit employees",Type=VGPermissionType.Permission)]> _
Private Sub MethodWithRestrictedAccess()
    MessageBox.Show("You can see this message only if you are an administrator")
End Sub

You can also use the VGPrincipalPermission class to check in your code whether the current principal has a permission or a role or is authenticated
Private Sub MethodWithRestrictedAccess()
    Dim PrincipalPerm1 As New VGPrincipalPermission("\Samples\Allow to call restricted method", VGPermissionType.Permission)
    Dim PrincipalPerm2 As New VGPrincipalPermission("Administrator", VGPermissionType.Role)
End Sub

Using URL authorization in ASP.Net context

In ASP.Net context, Visual Guard enables you to use the standard ASP.NET URL authorization module to allow or deny access to a particular directory by user name or role. For example, the following authorization section of a web.config file shows how to allow access to the members of  'Administrator' role and deny access to all other users
    <allow roles="Administrator"/>
    <deny users="*"/>
Visual Guard extends this standard ASP.NET URL authorization module and enables you to check Visual Guard permissions granted to the current user.
To do that, Visual Guard have to prefix the fullname of the permission to check by a percent character (%). Il also possible to use the Visual Guard unique id to specifiy a permission. In this case, you have to use the format: %{dddddddd-dddd-dddd-dddd-dddddddddddd }

The following sample shows how to allow access to user with the permission with a fullname equals to '\Employees\Allows to edit employees' and the permission with an id equal to 'e40b426a-9e78-4cb6-9f0d-ab047420f542'.
    <allow roles="Administrator"/>
    <deny users="%\Employees\Allows to edit employees,%{e40b426a-9e78-4cb6-9f0d-ab047420f542}"/>

Using ASP.NET login controls Web

Visual Guard enables you to use the standard LoginView control to display the appropriate content for a given role or user. It allows to use Visual Guards permission in place of role. In this case you have to prefix the fullname of the permission by a percent character (%). The syntax is the same as describe in the URL authorization chapter.

    <asp:LoginView ID="LoginView1" runat="server">
            <asp:RoleGroup Roles="%\Employees\Hide Salary">
            <asp:RoleGroup Roles="%{e40b426a-9e78-4cb6-9f0d-ab047420f542}">

Visual Guard is also compatible with all ASP.NET login controls and with the security trimming option of the standard SiteMapProvider to filter the content of a site map.

See Also

Debugging Visual Guard Security Actions
How Visual Guard secures an application
VGPrincipalPermission Class
VGPrincipalPermissionAttribute Class
Visual Guard Expression Language