Home > DeveloperSection > Beginner > Prevent Cross Site Scripting in Asp.Net Mvc 4

Prevent Cross Site Scripting in Asp.Net Mvc 4


ASP.NET MVC ASP.NET MVC 
Ratings:
1 Comment(s)
 4850  View(s)
Rate this:

Prevent Cross Site Scripting in Asp.Net Mvc 4

In this article, I’m explaining cross site scripting in asp.net mvc 4.

Introduction

Cross-Site Scripting (also known as XSS) is one of the most common application-layer web attacks. XSS commonly targets scripts embedded in a page which are executed on the client-side rather than on the server-side. The concept of XSS is to manipulate client-side scripts of a web application to execute in the manner desired by the malicious user. Such a manipulation can embed a script in a page which can be executed every time the page is loaded, or whenever an associated event is performed.

Cross Site Scripting allows an attacker to embed malicious JavaScript, VBScript, ActiveX, HTML, or Flash into a vulnerable dynamic page to fool the user, executing the script on his machine in order to gather data. The use of XSS might compromise private information, manipulate or steal cookies, create requests that can be mistaken for those of a valid user, or execute malicious code on the end-user systems. The data is usually formatted as a hyperlink containing malicious content and which is distributed over any possible means on the internet.

In a typical XSS attack the hacker infects a legitimate web page with his malicious client-side script. When a user visits this web page the script is downloaded to his browser and executed.

Example

Step 1

First create a table name “StudentTable” in the database like this:

Prevent Cross Site Scripting in Asp.Net Mvc 4

And add some dummy data in the table.

Step 2

Now create a basic asp.net mvc 4 application and add a class named “Student” like this:

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.ComponentModel.DataAnnotations.Schema;

using System.Linq;

using System.Web;

 

namespace XssMvcApp.Models

{

    [Table("StudentTable")]

    public class Student

    {

        [Key]

        public int StudentId { getset; }

        public string Name { getset; }

        public string Address { getset; }

    }

}

Step 3

Now add another class named “StudentContext” class to the project:

using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Web;

 

namespace XssMvcApp.Models

{

    public class StudentContext : DbContext

    {

        public DbSet<Student> Students { getset; }

    }

}

Step 4

Now add the connection string in the web.config file like this:

<connectionStrings>

      <add name="StudentContext" connectionString="Data Source=Uttam-PC4;Initial Catalog=SumitTesting;user id=usedr id;password=password;" providerName="System.Data.SqlClient"/>

  </connectionStrings>

 

Step 5

Now build the project and add a controller named “HomeController” to the project like this:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using XssMvcApp.Models;

 

namespace XssMvcApp.Controllers

{

    public class HomeController : Controller

    {

        StudentContext db = new StudentContext();

 

        public ActionResult Index()

        {

            return View(db.Students.ToList());

        }

 

        public ActionResult Create()

        {

            return View();

        }

 

        [HttpPost]

        public ActionResult Create(Student student)

        {

            if (ModelState.IsValid)

            {

                db.Students.Add(student);

                db.SaveChanges();

                return RedirectToAction("Index");

            }

            return View();

        }

 

    }

}

 

Step 6

Now add two views like this:

Index

@model IEnumerable<XssMvcApp.Models.Student>

 

@{

    ViewBag.Title = "Index";

}

 

<h2>Index</h2>

 

<p>

    @Html.ActionLink("Create New""Create")

</p>

<table>

    <tr>

        <th>

            @Html.DisplayNameFor(model => model.Name)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.Address)

        </th>

        <th></th>

    </tr>

 

@foreach (var item in Model) {

    <tr>

        <td>

            @Html.DisplayFor(modelItem => item.Name)

        </td>

        <td>

           @* @Html.Raw(item.Address.ToString())*@

            @Html.DisplayFor(modelItem => item.Address)

        </td>

      

    </tr>

}

 

</table>

 

Create

@model XssMvcApp.Models.Student

 

@{

    ViewBag.Title = "Create";

}

 

<h2>Create</h2>

 

@using (Html.BeginForm()) {

    @Html.AntiForgeryToken()

    @Html.ValidationSummary(true)

 

    <fieldset>

        <legend>Student</legend>

 

        <div class="editor-label">

            @Html.LabelFor(model => model.Name)

        </div>

        <div class="editor-field">

            @Html.TextBoxFor(model => model.Name, new { @style="width:300px;"})

            @Html.ValidationMessageFor(model => model.Name)

        </div>

 

        <div class="editor-label">

            @Html.LabelFor(model => model.Address)

        </div>

        <div class="editor-field">

            @Html.TextBoxFor(model => model.Address, new { @style="width:300px;"})

            @Html.ValidationMessageFor(model => model.Address)

        </div>

 

        <p>

            <input type="submit" value="Create" />

        </p>

    </fieldset>

}

 

<div>

    @Html.ActionLink("Back to List""Index")

</div>

 

 

 

 

Step 7

Now run the project:

Prevent Cross Site Scripting in Asp.Net Mvc 4

Click on create new to open the form:

Prevent Cross Site Scripting in Asp.Net Mvc 4

Fill the form with values, notice in the address field I have put a html anchor tag that will redirect to the mindstick website, now click on Create button:

Prevent Cross Site Scripting in Asp.Net Mvc 4

Your application will be crashed because it detected a dangerous request.

If you want to deal with the Html markups and want to allow the user to enter the html markups, then you can disable this prevention using [ValidateInput(false)] like this:

[HttpPost]

        [ValidateInput(false)]

        public ActionResult Create(Student student)

        {

            if (ModelState.IsValid)

            {

                db.Students.Add(student);

                db.SaveChanges();

                return RedirectToAction("Index");

            }

            return View();

        }

 

Step 8

Now run the application and enter the same data with html markups like this:

Prevent Cross Site Scripting in Asp.Net Mvc 4

Now click on create button:

Prevent Cross Site Scripting in Asp.Net Mvc 4

You record has been saved in the database with the html markups and the output will be like above because the Razor engine will encode the html markups.

 


Nice Article

By Ankita Pandey on   2 years ago
Nice Article

Don't want to miss updates? Please click the below button!

Follow MindStick