How to prevent cross-site scripting
Cross-site scripting can be prevented in the following way:
- Regular Expression Attributes
- Regular Expression Object Model
- HTML Encoding
- URL Encoding
Regular Expression
Using regular expression form inputs can be validated and the user's form denies special character, symbol and only allow required character before proceeding to the next page.
public class Student
{
// Allow up to 15 uppercase and lowercase
// characters. Use custom error.
[RegularExpression(@"^[a-zA-Z''-'\s]{1,15 }$",
ErrorMessage = "Characters are not allowed.")]
public object FirstName;
// Allow up to 15 uppercase and lowercase
// characters. Use standard error.
[RegularExpression(@"^[a-zA-Z''-'\s]{1,15}$")]
public object LastName;
}
Note:
Using Regular Expression, you can perform Client and server-side validation
Regular Expression Object Model
Using the regular expression object model, the developer can validate user inputs by calling static methods of the Regex class.
HTML Encoding
The Razor engine used in MVC automatically encodes all input sourced from variables so that malicious script will never be executed. <,”, >used in attack.
@{
var val = "<\"virat\">";
}
@val
So,Razor engine encode val in following format:
HTML file
<\"virat\">
< "Virat">
URL Encoding
Usually, the developer used plain text in the query string which causes an XSS attack so we should use an encoded query string. You can use the default encoder provided in
System.Text.Encodings.Web.
Example
public class HomeController: Controller
{
UrlEncoder _urlEncoder
public HomeController(UrlEncoder urlEncoder)
{
_urlEncoder = urlEncoder;
}
}
var example = "\"Virat kohli&\"";
var encodedValue = _urlEncoder.Encode(example);