Preventing Directory Listing – ASP.NET


Add the following lines to web.config:

  <location path=".">
      <directoryBrowse enabled="false" />


Setting Cookie Secure Flag – ASP.NET

Method #1 Setting Secure Property True

Create Cookie by setting secure property true:

HttpCookie cookie = new HttpCookie('name');
cookie.Secure = True;
cookie.Value = 'Value';

Method#2 Using web.config

Add the following codes to web.config

<httpCookies requireSSL="true" />


Setting the HttpOnly Flag – ASP.NET

Method #1

Add the following configuration to your web.config:

    <httpCookies httpOnlyCookies="true"  />

Method #2

In the code, use the System.Web.HttpCookie.HttpOnly property:

// Create an HttpOnly cookie.
HttpCookie theHttpOnlyCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
// Setting the HttpOnly value to true, makes
// this cookie accessible only to ASP.NET.
theHttpOnlyCookie.HttpOnly = true;
theHttpOnlyCookie.Name = "TheHttpOnlyCookie";
// Show the name of the HttpOnly cookie.


Clickjacking – ASP.NET Secure Coding

Method #1 Adding the X-Frame-Options in HTTP header

Add the code to the Application_BeginRequest method of global.asax file

void Application_BeginRequest(object sender, EventArgs e)
    HttpContext.Current.Response.AddHeader("x-frame-options", "DENY");

Method #2 Including frame busting code

<style> html{display : none ; } </style>
   if( self == top ) { = 'block' ; 
   } else {
       top.location = self.location ; 


Prevention of Web Page Caching – ASP.NET


Add the following codes into the page, in order to prevent the page being cached:

Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache"); 
Response.AppendHeader("Expires", "0");


Setting Session Timeout – ASP.NET

Method #1 in web.config 

Add the following codes in web.config (In this example it is the timeout set for 15 minutes.

    <sessionState timeout="15">

Method #2 in Global.asax

Add the following lines to  Session_Start event of Global.asax

void Session_Start(object sender, EventArgs e)
   Session.Timeout = 15;


SQLi – ASP.NET Secure Coding

Using Paramaterized Query/Prepared Statement

The use of parameterized stored procedures is an effective mechanism to avoid most forms of SQL Injection. Parameterized queries do proper substitution of arguments prior to running the SQL query. They completely remove the possibility of “dirty” input changing the meaning of your query.

// Build the query statement using parameterized query.

string sql = "SELECT UserId FROM Users WHERE " + "UserName = @UserName AND Password =@Password";
using (SqlCommand cmd = new SqlCommand(sql))
    // Create the parameter objects as specific as possible.  
    cmd.Parameters.Add("@UserName", System.Data.SqlDbType.NVarChar, 50);   
    cmd.Parameters.Add("@Password", System.Data.SqlDbType.NVarChar, 25);
    // Add the parameter values.  Validation should have already happened. 
    cmd.Parameters["@UserName"].Value = UserName; 
    cmd.Parameters["@Password"].Value = Password;  
    cmd.Connection = connnection; 
       var userId = cmd.ExecuteScalar();   
    catch (SqlException sx)   
       // Handle exceptions before moving on. 


Anti CSRF Token – ASP.NET

  1. Download AntiCSRF from the CSRF module for ASP.NET.
  2. In Project place Idunno.AntiCsrf.dll in Bin folder.
  3. Add a reference to the module into your web.config

 For IIS6/IIS7 in Classic ASP.NET mode:

            <add name="AntiCSRF" type="Idunno.AntiCsrf.AntiCsrfModule, Idunno.AntiCsrf"/>

For IIS7 in integrated pipeline mode:

          <add name="AntiCSRF" type="Idunno.AntiCsrf.AntiCsrfModule, Idunno.AntiCsrf"/>

4. Add the following settings to web.config

        <section name="csrfSettings"  type="Idunno.AntiCsrf.Configuration.CsrfSettings, Idunno.AntiCsrf" />   
    <csrfSettings cookieName="__CSRFCOOKIE" formFieldName="__CSRFTOKEN" detectionResult="RaiseException" errorPage="" />

5. Add the following codes in Page_Load Event.

   protected void Page_Load(object sender, EventArgs e)
    string page_name = System.IO.Path.GetFileName(System.
    string page_token = page_name + "_ID";
    Session[page_token] = CSRF_Token; 
    HiddenField1.value = CSRF_Token;

6. Add the following codes in Any Event.

   protected void Button1_Click(object sender, EventArgs e)
    string Page_Token =   System.IO.Path.GetFileName(System.Web.HttpContext.Current.Request.Url.AbsolutePath)+"_ID";
       if (HiddenField1.Value.ToString() != Session[Page_Token].ToString())


XSS – ASP.NET Secure Coding

Using Microsoft Anti XSS Library

  1. Download the AntiXss Library(AntiXSSLibrary.dll) from the Microsoft Web Protection Library.
  2. Right click the References node of the project to add a reference to the assembly.
  3. On particular cases :

Case #1

HTML escape before inserting untrusted data into HTML element content

string safedata = Microsoft.Security.Application.AntiXss.HtmlEncode( Request.QueryString[ "input" ] );
Response.Write(“<div>” + safedata + “</div>”);

Case #2

Attribute escape before inserting untrusted data into HTML common attributes

string safedata = Microsoft.Security.Application.AntiXss.HtmlAttributeEncode( Request.QueryString[ "input" ] );
Response.Write(‘<div name=”’ + safedata + ‘“>’);

Case #3

JavaScript escape before inserting untrusted data into HTML JavaScript data values

string safedata = Microsoft.Security.Application.AntiXss.JavaScriptEncode( Request.QueryString[ "input" ] );