mvc form submit
Generate Token on View
@using (Html.BeginForm("Manage", "Account")) { @Html.AntiForgeryToken() }Validate Toke on Action of your controller
Use
[ValidateAntiForgeryToken()]
on your action.
[HttpPost]
[ValidateInput(false)]
[ValidateInput(false)]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "ProductName,UnitPrice")] ProductModel productModel)
{
if (ModelState.IsValid)
{
......
}
return PartialView("_Create", productModel);
}
--------------------------------------------------------------------------------------------------------------
For Ajax submit
Add _Layout page
@functions{
public string TokenHeaderValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
<script>
$.ajaxSetup({
cache: false,
headers: {
"_RequestVerificationToken": '@TokenHeaderValue()'
}
});
</script>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class AjaxValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
var request = filterContext.HttpContext.Request;
// Only validate POSTs
if (request.HttpMethod == WebRequestMethods.Http.Post)
{
// Ajax POSTs and normal form posts have to be treated differently when it comes to validating the AntiForgeryToken
if (request.IsAjaxRequest())
{
var tokens = request.Headers["_RequestVerificationToken"].Split(':');
AntiForgery.Validate(tokens[0], tokens[1]);//cookieToken = tokens[0] , formToken = tokens[1]
}
else
{
new ValidateAntiForgeryTokenAttribute().OnAuthorization(filterContext);
}
}
}
}
======================================================
Cross-Site Request Forgery (CSRF)
Cross-Site Scripting (XSS) attacks
SubmittingMaliciousscripts in Input fields which lead to Error.
But now what if we want to put SCRIPT tag. For example programming sites like codeproject has a genuine need that end user should submit code and script snippets. In those scenarios we would like the end user to post code through the UI.
So lets us understand how to do the same but at the same time not compromise on security.
So we have four things via which we can allow scripts to be posted.
Solution: -
- [ValidateInput(false)]
- [AllowHtml]
- [RegularExpressionAttribute]
- AntiXSS Library
No comments:
Post a Comment