How to integrate ?

How to integrate in MVC ?

Estimated reading: 11 minutes 2050 views

To integrate Visual Guard in your MVC Application project you have to:

  • Add the assemblies of Visual Guard as references of your project.
  • Modify the “web.config” file of your application to integrate the Visual Guard module.
  • Integrate Visual Guard in the code of your application.
  • Create a Visual Guard repository and declare your application by using the Visual Guard console. This repository will contain all security items (users, roles, permissions…) of your application.
  • Generate the Visual Guard configuration files by using the Visual Guard console. These configuration files will be needed to connect your application to the repository.
  • Grant read/write permissions to the repository.


Integration Demo

Referencing Visual Guard assemblies

  • Opens the solution of your project in Visual Studio.
  • In the solution explorer, expands the project node.
  • Right-click the Project node for the project and select
    Add Reference
    from the shortcut menu.
  • In .Net tab, select the 5 assemblies
    1. Novalys.VisualGuard.Security
    2. Novalys.VisualGuard.Security.WebForm
    3. Novalys.VisualGuard.Security.WebMvc
    4. Novalys.VisualGuard.Security.<RepositoryType> (Files, SQLServer or Oracle)
    5. Novalys.VisualGuard.Security.<ApplicationFrameworkType> (Depending on type of application’s framework, whether .NetFramework or .NetCore)

    And, then click the Select button, and then click the OK button

Add ReferencesASPMVC
  • Novalys.VisualGuard.Security contains the main Visual Guard classes.
  • Novalys.VisualGuard.Security.Files contains the classes needed to access to a file based repository.
  • Novalys.VisualGuard.Security.SQLServer contains the classes needed to access to a repository stored in a Microsoft SQLServer database (SQLServer 2005 or higher). Available only in Visual Guard Enterprise Edition
  • Novalys.VisualGuard.Security.Oracle contains the classes needed to access to a repository stored in an Oracle database (9i or higher). Available only in Visual Guard Enterprise Edition
  • Novalys.VisualGuard.Security.WebForm contains the classes needed for ASP.Net application. You must reference this assembly in ASP.Net web application or WebService project.
  • Novalys.VisualGuard.Security.WebMvc contains the classes needed for MVC application. You must reference this assembly in MVC application along with
    Novalys.VisualGuard.Security.WebForm assembly.
  • Novalys.VisualGuard.Security.NetFramework contains all classes required to support .Net Framework applications. This assembly is needed only if you want to integrate Visual Guard in .net framework applications.
  • Novalys.VisualGuard.Security.Core contains all classes required to support .Net Core applications. This assembly is needed only if you want to integrate Visual Guard in .net core applications.

Modifying the “web.config” file of your application

  • Open the “web.config” file of your application or add a new one to your project.
  • Add the following line of code in the <httpModules> node.
  • XML
<add type="Novalys.VisualGuard.Security.WebForm.VGHttpModule,Novalys.VisualGuard.Security.WebForm" name="VGModule"/>
  • XML
<configuration>
	<system.web>
		... 
		<httpModules>
			<add type= "Novalys.VisualGuard.Security.WebForm.VGHttpModule,Novalys.VisualGuard.Security.WebForm" name="VGModule" />
		</httpModules>
		... 
	</system.web>
</configuration>
  • XML
<configuration>
	<system.webserver>
		... 
		<!--  Integrated Mode -->
		<modules runAllManagedModulesForAllRequests="true" > 
			<add type= "Novalys.VisualGuard.Security.WebForm.VGHttpModule,Novalys.VisualGuard.Security.WebForm" name="VGModule"/> 
		</modules>
		...
	</system.webserver>
</configuration>
  • Open the Visual Guard console and connect to the repository associated to your application.
  • Create a new role in your application with a permission set containing permissions for an anonymous user.
  • Select the item corresponding to your application and, in the property “Anonymous role”, select the role created above.
  • To take into account this modification in your application, you must regenerate the Visual Guard configuration files of your application or edit them and change the option anonymousSessionSupported.
  • Modify your authorization section of web.config file in order to allow anonymous access to your application.

Visual-Guard Configuration

Allow Anonymous Access

  • XML
<configuration>
	<configSections>
		<section name="VGWebConfiguration" type="Novalys.VisualGuard.Security.WebForm.VGWebConfiguration" />
	</configSections>
	...
	<VGWebConfiguration excludeExtension=".css,.png,.js,.gif,.jpg,.Gif">
		<ExcludePages>
			<add Url="^~/$" />
			<add Url="~/Account/Login" />
		</ExcludePages>
		<VGCookieConfig Domain=".vg.local" DomainScope="WebSSO" AutoRedirect="true" AuthenticationUrl="http://vg.local/webApp/Account/Login" />
	</VGWebConfiguration>
</configuration>

Mixed Mode Authentication 

  • Make sure to enable “Windows Authentication”. You can enable it from Windows features > Internet Information Services > World Wide Web Services > Security > Windows Authentication.
  • Make sure to mark Authentication – Windows to Read/Write. You can mark it from IIS Root > Feature Delegation > mark Authentication – Windows to Read/Write.
  • Set authentication mode to “None” in web.config
  • XML
<authentication mode="None" />
  • Set modules and security tag nuder system.webServer in web.config as below:
  • XML
<system.webServer> <validation validateIntegratedModeConfiguration="false" /> <modules runAllManagedModulesForAllRequests="true"> <remove name="FormsAuthentication" /> <add type="Novalys.VisualGuard.Security.WebForm.VGHttpModule,Novalys.VisualGuard.Security.WebForm" name="VGModule" /> </modules> <security> <authentication> <windowsAuthentication enabled="true" /> </authentication> </security> </system.webServer>

Web SSO

  • If the tag VGCookieConfig is not defined, Visual Guard Authentication restricts its scope for the website only.
  • Value for the property Domain restricts Visual Guard Authentication to that particular domain. Hence, all web application coming under that domain will be authenticated.
  • Value for the property DomainScope defines the scope of Visual Guard Authentication.
    • Website: Restricts authentication only for current web application.
    • WebSSO: Restricts authentication for all web applications which comes under defined domain. Signing out from one application results sign out from all web applications.
    • All: Restricts authentication for all web applications which comes under defined domain. But here signing out from one application would not affect other applications.
  • If the value of property AutoRedirect is true and the user is not authenticate VG redirects the user to AuthenticationUrl.
  • Value of the property AuthenticationUrl gets or sets the url for authentication.
  • XML
<configuration>
	<VGWebConfiguration excludeExtension=".css,.png,.js,.gif,.jpg,.Gif">
		<ExcludePages>
			<add Url="^~/$" />
			<add Url="~/Account/Login" />
		</ExcludePages>
		<VGCookieConfig Domain=".vg.local" DomainScope="WebSSO | Website | All" AutoRedirect="true" AuthenticationUrl="http://vg.local/webApp/Account/Login" />
	</VGWebConfiguration>
</configuration>

Configuring Membership

  • XML
<configuration>
	<system.web>
		...
		<roleManager defaultProvider="VGRoleProvider" enabled="true"> 
			<providers> 
				<add name="VGRoleProvider" type="Novalys.VisualGuard.Security.WebForm.VGRoleProvider, Novalys.VisualGuard.Security.WebForm" /> 
			</providers>
		</roleManager>
		<membership defaultProvider="VGMemberShipProvider">
			<providers>
				<add name="VGMemberShipProvider" type="Novalys.VisualGuard.Security.WebForm.VGMemberShipProvider, Novalys.VisualGuard.Security.WebForm" /> 
			</providers>
		</membership>
		... 
	</system.web>
</configuration>

Integrating Visual Guard in your code

  • When you want to use the Form Authentication mode, you must create authentication form that will be used to identify the users.
  • When you want to secure a WebService, a custom class or custom control, you must call Visual Guard to set the security of this object (Form and Master class are automatically secured by Visual Guard).
  • When you want to check if a user has a specific permission or a specific role, you can use Novalys.VisualGuard.Security.VGSecurityManager.Principal or use the property HttpContext.User.

To create a Login page

  • C#
  • VB
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{ 
     if (ModelState.IsValid) 
     {
          if (!VGSecurityManager.Authenticate(model.UserName, model.Password, VGAuthenticationMode.VisualGuard).IsFailed) 
          { 
               VGFormsAuthentication.SignIn(); 
               if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) 
               { 
                     return Redirect(returnUrl); 
               } 
               else 
               { 
                     return RedirectToAction("Index", "Home"); 
               } 
          } 
          else 
          { 
               ModelState.AddModelError("", "The user name or password provided is incorrect."); 
          } 
     } 
     return View(model); 
} 
public ActionResult LogOff() 
{ 
     VGFormsAuthentication.SignOut(); 
     return RedirectToAction("Index", "Home"); 
}
<HttpPost>
Public Function LogOn(ByVal model As LogOnModel, ByVal returnUrl As String) As ActionResult

    If ModelState.IsValid Then

        If Not VGSecurityManager.Authenticate(model.UserName, model.Password, VGAuthenticationMode.VisualGuard).IsFailed Then

            VGFormsAuthentication.SignIn()

            If Url.IsLocalUrl(returnUrl) AndAlso returnUrl.Length > 1 AndAlso returnUrl.StartsWith("/") _
                AndAlso Not returnUrl.StartsWith("//") AndAlso Not returnUrl.StartsWith("/\") Then

                Return Redirect(returnUrl)

            Else
                Return RedirectToAction("Index", "Home")
            End If

        Else
            ModelState.AddModelError("", "The user name or password provided is incorrect.")
        End If

    End If

    Return View(model)

End Function


Public Function LogOff() As ActionResult
    FormsAuthentication.SignOut()
    Return RedirectToAction("Index", "Home")
End Function

To secure your application objects

How to filter granted roles

  • C#
  • VB
void VGModule_PermissionLoading(object sender, VGPermissionsLoadingEventArgs args) 
{
    if(e.Roles.Length > 1) 
    { 
		Novalys.VisualGuard.Security.VGGrantedRole[] selectedRoles = new Novalys.VisualGuard.Security.VGGrantedRole[1]; 
		foreach (Novalys.VisualGuard.Security.VGGrantedRole role in e.Roles)
		{ 
			if (role.Name ==  "Administrator") 
			{ 
				selectedRoles[0] = role;
				break; 
			} 
			else if (role.Name == "Member") 
			{
				selectedRoles[0] = role; 
				break; 
			}
		}
		if (selectedRoles[0] == null) 
		{
			e.Status = Novalys.VisualGuard.Security.VGAuthorizationStatus.ProcessCanceled;
		}
		else 
		{
			e.Roles = selectedRoles;
		}
    }
}
Sub VGModule_PermissionLoading(ByVal sender As Object, ByVal e As VGPermissionsLoadingEventArgs)

    If e.Roles.Length > 1 Then

        Dim selectedRoles(0) As Novalys.VisualGuard.Security.VGGrantedRole

        For Each role As Novalys.VisualGuard.Security.VGGrantedRole In e.Roles

            If role.Name = "Administrator" Then
                selectedRoles(0) = role
                Exit For

            ElseIf role.Name = "Member" Then
                selectedRoles(0) = role
                Exit For

            End If

        Next

        If selectedRoles(0) Is Nothing Then
            e.Status = Novalys.VisualGuard.Security.VGAuthorizationStatus.ProcessCanceled
        Else
            e.Roles = selectedRoles
        End If

    End If

End Sub

Creating a repository and declaring the application

Securing MVC application

  • Connect to the Repository.
  • Expand your MVC application node.
  • Right click on Permission node and click “Create Permission”.
  • Give valid name to the newly created permission.

Implementing permission on Property Action

  • C#
  • VB
public class ProductController: Controller, VGISecurable
{
    public ProductController()      
    {
        VGSecurityManager.SetSecurity(this);      
    }
}
Public Class ProductController
    Inherits Controller
    Implements VGISecurable

    Public Sub New()
        VGSecurityManager.SetSecurity(Me)
    End Sub

End Class
  1. Create a boolean property inside the code.
  2. Create a permission in your application in Visual Guard Win Console.
  3. Right click and create “Property Action” and follow the screen.
  4. Finally select the property which you have created inside the code and assign either True of False

Implementing permission on Action Link

  • C#
  • VB
@using Novalys.VisualGuard.Security.Web
@Html.VGActionLink(@"/Employees/Allow to edit and delete employee", "Edit", "Edit", "Edit", new { id = item.EmployeeID })
@Imports Novalys.VisualGuard.Security.Web
@Html.VGActionLink(@"/Employees/Allow to edit and delete employee", "Edit", "Edit", "Edit", new { id = item.EmployeeID })

Implementing permission if has permission

  • C#
  • VB
@using Novalys.VisualGuard.Security.Web
@if (this.HasPermission("/Employees/Allow to administrate employees")) 
{ 
 @Html.ActionLink("Edit or create employee", "Index", "Employee", null, null)
} 
else 
{ 
     @: Edit or create employee 
}
@Imports Novalys.VisualGuard.Security.Web

@if Me.HasPermission("/Employees/Allow to administrate employees") Then
    @Html.ActionLink("Edit or create employee", "Index", "Employee")
Else
    @:Edit or create employee
End If

Implementing permission if is in role

  • C#
  • VB
@using Novalys.VisualGuard.Security.Web
@if (this.HasPermission("/Employees/Allow to administrate employees")) 
{ 
	@Html.ActionLink("Edit or create employee", "Index", "Employee", null, null)
} 
else 
{ 
    @: Edit or create employee 
}
@Imports Novalys.VisualGuard.Security.Web

@If Me.IsInRole("Developer") Then
    @Html.ActionLink("Edit or create employee", "Index", "Employee")
Else
    @:Edit or create employee
End If

Implementing VGWebAuthorize attribute

  • C#
  • VB
[VGWebAuthorize(Roles = "Admin")]
public class EmployeeController : Controller
{
}
<VGWebAuthorize(Roles:="Admin")>
Public Class EmployeeController
    Inherits Controller
End Class

Description: Only the loggedin user with “Admin” role can access.

  • C#
  • VB
[VGAuthorize(Permissions = "CanGetAllRoles", Roles = "RoleManager")]
public ActionResult GetRoles()
{
    return View();
}
<VGAuthorize(Permissions:="CanGetAllRoles", Roles:="RoleManager")>
Public Function GetRoles() As ActionResult
    Return View()
End Function

Description: Only the loggedin user with Permission “CanGetAllRoles” and Role “RoleManager” can access.

  • C#
  • VB
[VGWebAuthorize(Permissions = "ReadOnly, CanGetById")]
public ActionResult GetPermissions()
{
    return View();
}
<VGWebAuthorize(Permissions:="ReadOnly, CanGetById")>
Public Function GetPermissions() As ActionResult
    Return View()
End Function

Description: Only the logged in user with permissions “ReadOnly” or “CanGetById” can access.

Complete Example

  • C#
  • VB
[VGWebAuthorize(Roles = "Admin")]
public class ProductionController : ApiController
{
    Product[] products = new Product[] 
    { 
      new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
      new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
      new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
    };
	
    [VGWebAuthorize(Permissions = "CanGetAllRoles", Roles = "RoleManager")]
    public IEnumerable<Product> GetAllProducts()
    {
       return products;
    }
	
    [VGWebAuthorize(Permissions = "ReadOnly" )]
    [VGWebAuthorize(Permissions = "CanGetById")] 
    public Product GetProductById(int id)
    {
       var product = products.FirstOrDefault((p) => p.Id == id);
       if (product == null)
       {
           throw new HttpResponseException(HttpStatusCode.NotFound);
       }
       return product;
    }
}
Imports System.Net
Imports System.Web.Http
Imports Novalys.VisualGuard.Security.Web
Imports System.Linq

<VGWebAuthorize(Roles:="Admin")>
Public Class ProductionController
    Inherits ApiController

    Private products As Product() = New Product() {
        New Product() With {
            .Id = 1,
            .Name = "Tomato Soup",
            .Category = "Groceries",
            .Price = 1D
        },
        New Product() With {
            .Id = 2,
            .Name = "Yo-yo",
            .Category = "Toys",
            .Price = 3.75D
        },
        New Product() With {
            .Id = 3,
            .Name = "Hammer",
            .Category = "Hardware",
            .Price = 16.99D
        }
    }

    <VGWebAuthorize(Permissions:="CanGetAllRoles", Roles:="RoleManager")>
    Public Function GetAllProducts() As IEnumerable(Of Product)
        Return products
    End Function

    <VGWebAuthorize(Permissions:="ReadOnly")>
    <VGWebAuthorize(Permissions:="CanGetById")>
    Public Function GetProductById(id As Integer) As Product

        Dim product = products.FirstOrDefault(Function(p) p.Id = id)

        If product Is Nothing Then
            Throw New HttpResponseException(HttpStatusCode.NotFound)
        End If

        Return product

    End Function

End Class

Granting Read/Write permission to the Repository

  • Open the Explorer.
  • Right click the directory containing the repository data then select the menu “Properties”.
  • In the “Security” tab, click on the “Add” button and select the user for which you want to grant the permission (i.e. MACHINE\ASPNET) then click ok.
  • In the list of permissions, click the option “Modify” then click on the “OK” button.