Monday, December 26, 2016

What is Cross Site Scripting Attack (XSS) 

Cross Site Scripting is also called XSS.  It is a security attack mostly on web applications.  XSS allows hackers to inject malicious javascript into web pages and later on when other users views those web pages, injected javascript code is executed and hackers steal their confidential data e.g. session cookies and with the stolen session cookies data, hackers can easily log on to the others users account without knowing user id and password.  If user is doing any financial / banking transactions, stolen session cookies data may also be user credit /debit card number, PIN etc.

How to avoid XSS in  ASP.Net MVC ?

By default ASP.Net MVC provides XSS security and in case user tries to update javascript or HTML code, ASP.Net MVC will throw error message alongwith detailed stack trace.



 

But what will we do when there is a requirement to update html formatted sting in database.  For doing this, we need to disable XSS security at controller action method.

To disable XSS at ASP.Net Controller action method, we need to set  [ValidateInput(false)] at controller action method level.


By setting [ValidateInput(false)], we can disable XSS check but user still can enter javascript along with HTML and our basic requirement is to enter HTML only.  For example we want to enter like :

We are entering <b>HTML encoded</b> text.  In this text we are using <b> html tag to bold the text.  We need to write logic to accept <b> html tag.  To achieve this we need to provide filter at controller action method and dynamically encode as given below :-