How to secure your MVC4 application?

How to secure your MVC application?

Why use Visual-Guard in your MVC application?

This document describes how easy it is to secure your MVC projects with Visual Guard

Visual Guard is a ready to use Access Control solution that allows you to secure MVC applications without coding.

Save time during application development, and standardize security across the company with Visual Guard. It supports various application types: Winform, Webform, Webservices, SaaS, Multi-tenant, etc.

Visual Guard modules provide functionality for:

  • User management
  • Authentication
  • Permissions
  • Security Audit of user rights and operations

Prerequisites

To integrate Visual Guard in your MVC application, you need to ensure that the following points are met:

  1. Give reference to all required Visual Guard assemblies into your project and make sure to mark “Copy Local” to true.
  2. Make necessary changes, such as Visual Guard Configuration sections, in web.config.
  3. Build the project.
  4. Add MVC application as new ASP.Net Web application in the Visual Guard Repository.
  5. Generate the VG config files.

How to login into your application?

All business applications require a secure way to restrict access to resources, making them accessible to only authenticated users. Before we proceed, make sure the prerequisites are implemented and the user(s) have permission to access the application.

Here is the code written in AccountController which will be executed once "Log In" button is clicked.

Code Snippet

  1. [HttpPost]
  2. [AllowAnonymous]
  3. [ValidateAntiForgeryToken]
  4. public ActionResult Login(LoginModel model, string returnUrl)
  5. {
  6.    if (ModelState.IsValid)
  7.    {
  8.        String userName = model.UserName;
  9.        String password = model.Password;
  10.        VGAuthenticationState state =VGSecurityManager.Runtime.Authenticate(userName, password,
  11.        VGAuthenticationMode.VisualGuard);
  12.        if (!state.IsFailed)
  13.        {
  14.            VGFormsAuthentication.SignIn();
  15.            return RedirectToLocal(returnUrl);
  16.        }
  17.    }
  18.            // If we got this far, something failed, redisplay form
  19.    ModelState.AddModelError("", "The user name or password provided is incorrect.");
  20.    return View(model);
  21.    }

The method "Runtime.Authenticate" takes username, password and authentication mode as a parameter and returns its status after execution based on many criterias. The authentication mode here can be VisualGuard, WindowsByCredential, Database, etc. Once the authentication status is "Success", "VGFormsAuthentication.SignIn" method must be called. It sets an authentication token in a cookie which lets the application know, on subsequent requests, about user authentication.

How to implement Single Sign On in your application?

The objective of SSO is to allow users access to all applications with a single account. It provides a unified mechanism to manage the authentication of users and determine user access to applications and data.

SSO integration should not impose significant modifications to the application and should be the same no matter the type of application or development technology used.

Visual Guard provides a coherent authentication strategy and framework for all applications and websites secured by the system.

  • Windows Account
    When an SSO session is based on a Windows session, the standard Windows login window will be used
  • ADFS Account
  • Visual Guard Account
  • Database Account
    When an SSO session is based on ADFS/Visual Guard/Database account, a ready to use login form is provided to support the SSO security system. The user can choose the type of account before entering their credentials.

To enable SSO in your application, you must enable VGCookieConfig in web.config under VGWebConfiguration section.

Code Snippet

<VGCookieConfig Domain=".vg.local" DomainScope="WebSSO" AutoRedirect="true" AuthenticationUrl="http://vg.local/webApp/Account/Login" />

Properties


Name Description
Domain It restricts Visual Guard Authentication to that particular domain. Hence, all web applications coming under that domain will be authenticated.
DomainScope

It defines the scope of Visual Guard Authentication

    • Website:  Restricts authentication only for current web application.

    • WebSSO:  Restricts authentication for all web applications under a defined domain. Signing out from one application results in the sign out from all web applications.

    • All:  Restricts authentication for all web applications under a defined domain. But here signing out from one application will not affect other applications.

How to secure your Razor page?

Visual Guard has extended the helper class to manage security and access control using the Razor View Engine. Now, you can easily secure your razor view page implementing the below methods.

How to use IsInRole?

Once the user is authenticated, you can check whether the logged in user is in a specific role or not. You can easily check using the code below.

Code Snippet

1. @if (this.IsInRole("Administrator"))
2. {
3.      //..
4. }

How to use HasPermission?

Along with checking the role of an authenticated user, you can also check whether the currently logged in user has a specific permission or not. You can check using the code below.

Code Snippet

  1. @if (this.HasPermission("IsAdministrator"))
  2. {
  3.      //..
  4. }

How to use IsAuthenticated?

Using the IsAuthenticated method, you can check whether the user is authenticated or not. Based on that you can enable some controls.

Code Snippet

  1. @if (this.IsAuthenticated())
  2. {
  3.      //..
  4. }

How to use VGActionLink?

Similar to ActionLink link button, Visual Guard has a VGActionLink which takes the permission parameter based on which you can hide/show link button.

Code Snippet

  1. @Html.VGActionLink("<Full Permission Name>", "<Text to Show>", " ", "<Action Name>", "<Controller Name>")

How to secure your Controller/Action?

The VGWebAuthorize attribute, when applied on a controller or actions, forbids unauthorized access. If you mark a controller with the VGAuthorize attribute, all actions in this controller are restricted.

Any attempts to access a controller or an action secured by VGWebAuthorize attribute will throw an UnAuthorize 401 status and take you to a standard login page. You can restrict a controller/an action based on users, roles and permissions.

Code Snippet

  1. [VGWebAuthorize(Roles="Admin,Manager")]
  2. [VGWebAuthorize(Users="jsmith,robin")]
  3. [VGWebAuthorize(Permissions="IsAdmin,IsManager")]
  4. public class AccountController : Controller

You can pass multiple roles, users or permissions so that Visual Guard combines and restricts the entity accordingly.

How to secure the data access layer?

The security of databases has become important as enterprises consider the data as assets that are critical to operations. One of the common requirements for most applications is filtering rows based on data of current user or securing LINQ in modern times. Visual Guard is capable of achiving this.

A user can secure the data access layer based on the property assigned from Visual Guard. Also, they can pass the expression to a property or add an attribtue of any data type to a permission.

Code Snippet

  1. [VGPrincipalPermission(SecurityAction.Demand, Name = "canReadProduct", Type = VGPermissionType.Permission)] //Secure the stored procedure
  2. public IEnumerable <Product> getProduct()
  3. {
  4.            var result =  dc.selectProduct();
  5.            return result;
  6. }

How to apply a dynamic action?

To dynamically secure a property from Visual Guard, you can assign the property of the controller as below:

Code Snippet

  1. public class ResultsController : Controller, VGISecurable
  2.    {
  3.        public bool CanViewProfit { get; set; }
  4.        public ResultsController()
  5.        {
  6.            VGSecurityManager.SetSecurity(this);
  7.            ViewBag.CanViewProfit = this.CanViewProfit;
  8.        }        
  9.        public ActionResult Index()
  10.        {
  11.            return View();
  12.        }
  13.    }

View:
@if (ViewBag.CanViewProfit)
{
          @: ...
}

How to create a web portal for my company?

Every big organization has multiple websites, either by department or location wherein they have an individual login page for user authentication and the user needs to login multple times with the same credentials. The Visual Guard Web Portal provides the solution for a scenario where there is only one login page for all secured websites integrated into Visual Guard. A user of multiple websites secured by Visual Guard will log in when they enter the first site.

Visual Guard provides two possible ways to achieve this:

  1. Not having a web portal login page.
    The Visual Guard web portal is provided out-of-the box to manage SSO user authentication. It installs a new web application which works as a web portal login page wherein a user of multiple websites secured by Visual Guard will log in when they enter the first site. Later, they can directly access other websites without entering credentials assuming they have permissions for the current application.

  2. Having own web portal login page.
    If you have your web application with a login page and want it to work as a web portal login page, simply configure web.config in all the secured websites. Please refer to the “How to implement Single Sign On in your application?” paragraph for further information.

Web Portal with Visual Guard

How to jump from website A to website B without authenticating again?

After successful authentication on one site, Visual Guard creates the security token that allows the security system to uniquely identify each session. You can pass this token to another web site and Visual Guard will automatically identify whether the user has permission to access this application or not.

How to exclude MVC views from security?

By default, Visual Guard secures all views. You can however exclude some views from security. For example: Root page, Login Page and Create User page do not require security. You can exclude it from the web.config section as below:

Code Snippet

  1. <configSections>
  2.    <section name="VGWebConfiguration" type="Novalys.VisualGuard.Security.WebForm.VGWebConfiguration" />
  3. </configSections>

Code Snippet

  1. <VGWebConfiguration excludeExtension=".css,.png,.js,.gif,.Gif" AutoLoginPage="True">
  2.    <ExcludePages>
  3.        <add Url="~/Images/.*.jpg" />
  4.        <add Url="^~/$" />
  5.        <add Url="~/Account/Login" />
  6.    </ExcludePages>
  7. </VGWebConfiguration>

You need to define ‘VGWebConfiguration’ section to activate configuration in the application and then in the next code snippet you can see how you can exclude extension from security. If ‘AutoLoginPage=True’, it will redirect the browser to the login URL.

How to exclude a file extension from security?

By default, Visual Guard secures all file extensions. You can however exclude some extensions from security. For example: CSS, jpg, gif, etc. do not require security. You can exclude it from the web.config section as below:

Code Snippet

  1. <configSections>
  2.    <section name="VGWebConfiguration" type="Novalys.VisualGuard.Security.WebForm.VGWebConfiguration" />
  3.  </configSections>

Code Snippet

  1. <VGWebConfiguration excludeExtension=".css,.png,.js,.gif,.Gif" AutoLoginPage="True">
  2. </VGWebConfiguration>

You need to define ‘VGWebConfiguration’ section to activate configuration in the application and then in the next code snippet you can see how you can exclude extension from security. If ‘AutoLoginPage=True’, it will redirect the browser to the login URL.

How to improve performance while applying the security?

If you have more than 1000 connections per second, you need to set some preferences in Visual Guard.

By default Visual Guard secures all components requested by the browser.

  1. Remove all files with extensions that don’t need to be secure by Visual Guard like .js, .png, .gif.
  2. Set your VG cache duration, around 45 minutes.
  3. Set  AllowAnonymous attribute on controllers/actions where security is not needed.

How to secure the Web API controller?

To control access on a Web API, you need authentication and authorization. In most of the cases, Web API assumes that the authentication would happen on host side which creates IPrincipal object representing the security context. But in other cases where a user wants to do authentication on Web API side, he can simply authenticate with Visual Guard and return token to the host. Later, the host can send this token with requests, for example a querystring, to call Web API actions.

Code Snippet

  1. public String GetAuthToken(LoginModel model)
  2.        {
  3.            String userName = model.UserName;
  4.            String password = model.Password;
  5.            String token = String.Empty;
  6.            VGAuthenticationState state = VGSecurityManager.Authenticate(userName, password, VGAuthenticationMode.VisualGuard);
  7.            if (!state.IsFailed)
  8.            {
  9.                VGFormsAuthentication.SignIn();
  10.                token = VGSecurityManager.Runtime.Principal.Token.Data;
  11.            }
  12.            return token;
  13.        }

Later, to call an action with token, it can be called as “<baseurl>/api/production/getall?vgtoken=xxxxxxxx”

Visual Guard provides an attribute authorization filter “VGAuthorize” which checks whether the user is authenticated and if not then returns the status code 401. Once it checks it is authenticated, it checks for authorization for users, roles and permissions.

Code Snippet

  1. [VGAuthorize(Permissions = "CanGetAllProducts", Roles = "RoleManager")]
  2.        public IEnumerable<Product> GetAllProducts()
  3.        {
  4.            return products;
  5.        }