How to protect $.post posting in mvc

anandsrivastav1087
anandsr...
Member
2 Points
1 Posts

How to protect $.post posting in mvc

Views: 9592
Total Answered: 1
Total Marked As Answer: 0
Posted On: 01-Jun-2015 23:27

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
Teacher
4822 Points
23 Posts
         

Hi Anand,

If you talking about preventing Cross-Site Request Forgery (CSRF) then use ASP.NET MVC’s AntiForgeryToken() helper or use captcha

MVC’s AntiForgeryToken():

ASP.NET MVC package includes a set of helpers that give you a means to detect and block CSRF using the “user-specific tokens” technique.

To use these helpers to protect a particular form, put an Html.AntiForgeryToken() into the form, e.g.,

<% using(Html.BeginForm("UserProfile", "SubmitUpdate")) { %>
<%= Html.AntiForgeryToken() %>
<!-- rest of form goes here -->
<% } %>

 

This will output something like the following:

<form action="/UserProfile/SubmitUpdate" method="post">
    <input name="__RequestVerificationToken" type="hidden" value="saTFWpkKN0BYazFtN6c4YbZAmsEwG0srqlUqqloi/fVgeV2ciIFVmelvzwRZpArs" />
    <!-- rest of form goes here -->
</form>

At the same time, Html.AntiForgeryToken() will give the visitor a cookie called __RequestVerificationToken, with the same value as the random hidden value shown above.

Next, to validate an incoming form post, add the [ValidateAntiForgeryToken] filter to your target action method. For example,

[ValidateAntiForgeryToken]
public ViewResult SubmitUpdate()
{
// ... etc
}

This is an authorization filter that checks that:
•The incoming request has a cookie called __RequestVerificationToken
•The incoming request has a Request.Form entry called __RequestVerificationToken
•These cookie and Request.Form values match

Assuming all is well, the request goes through as normal. But if not, boom!, there’s an authorization failure with message “A required anti-forgery token was not supplied or was invalid”.

 

 

Posted On: 01-Jun-2015 14:56
 Log In to Chat