How to prevent cross site scripting in MVC when AJAX request is sent by another website - asp.net-mvc

I have an HTML form in MVC ASP.NET which the user fills out and the request goes to the server [AJAX] then we send a mail them to inform them. I use the hidden key to store information on the page.
I find that someone changed the key and then clicked then it's a problem that the mail go to other who are unknown for this case.
How can I be sure that nobody changes the hidden key and request is valid. The thing I want to do that HTML. antioforeignkey who is suitable for that.
But how can I implement antiforeignkey when I send AJAX request to server.
Are there any tricks to solve this problem in MVC?

Check out this link: http://blog.stevensanderson.com/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/
This link will help with AntiForgeryToken and Ajax calls: http://blogs.us.sogeti.com/swilliams/2009/05/14/mvc-ndash-using-antiforgerytoken-over-ajax/
Be sure to add #Html.AntiForgeryToken() to your form then you can use jQuery to pull that value. With the value you can then add it to the data attribute of your jQuery Ajax call.
var token = $('input[name=__RequestVerificationToken]').val();

Related

What is the use of #Html.AntiForgeryToken()?

Why we need to use #Html.AntiForgeryToken()?
I searched but I didn't get satisfactory answer.
This is a security feature to help protect your application against cross-site request forgery.
Example:
Let's assume you have a register functionality in your web app. You have an AccountController (example.com/account/register) where you expect people to submit their info. Normally before someone posts the registration information needs to visit the actual (example.com/account/register) than submit the form.
Let say I am a bad guy and I want to flood your server with junk info all I need to do is just keep posting directly to (example.com/account/register) without visiting your site. So in order to stop me you implement AntiForgeryToken so you can make it sure I visited the page before I submitted the registration information.
Another example is http://www.binaryintellect.net/articles/20e546b4-3ae9-416b-878e-5b12434fe7a6.aspx.
This is to prevent Cross-site request forgery in your MVC application. This is part of the OWASP Top 10 and it is vital in terms of web security. Using the #Html.AntiforgeryToken() method will generate a token per every request so then no one can forge a form post.
What is the use of #Html.AntiForgeryToken()?
Live - Scenario :
Suppose, you are logged into your bank account and are going to transfer some money to your friend. A hacker knows that you are logged in and also knows the URL of the money transfer submission. Suddenly, you get an email and check it. You see an image and by mistake, you click on that. Then, after a minute or so, you get another message that some amount has been deducted from your account. Actually, that image had been sent by the hacker and behind that image a URL has been submitted on your click.
So that we use AntiForgeryToken() in application prevent from hackers.
Antiforgery() is for stopping robotic fill up of any forms. Which will stop adding data without getting into the form
AntiForgeryToken is a security token generated by the .Net Core web application, which is used to validate a post request to guard against Cross-Site Request.
AntiforgeryToken used for validating the post request. So if we access an MVC or RazorPages view which contains the form element with an attribute 'method="post"' then the view gets rendered with an automatic generated AntiforgertyToken value, which gets injected into the form as hidden input field.

HTTP POST Request, HTML Form input (login: user/password) browser simulation

I'm trying to login to a website (http://www.meo.pt/ver/Pages/login.aspx) from within my application so that I can access the program listing, etc, I searched in the page source code for the html for of the username textbox and password textbox input.
<input name="ctl00$SPWebPartManager1$g_cb264700_1517_426f_926d_3ca40934a6fd$ctl00$EditModePanel1$txtUserName"
type="text"
id="ctl00_SPWebPartManager1_g_cb264700_1517_426f_926d_3ca40934a6fd_ctl00_EditModePanel1_txtUserName"
class="forms_login" />
I used the value in name and set the content of that key with the username and the same form the password. Then made a POST request to http://www.meo.pt/ver/Pages/login.aspx from which I got a response containing the HTML source of the same page, so login wasn't successful. I don't think the server even considered it a login try.
My question is how should I set the POST request values to make this work?
I'm using ASIHTTPRequest for iPhone.
My guess is that it's cookie-related: the page sends a cookie when it appears and requires that cookie along with the username and password. Odds are good that every POST and GET returns a cookie along with the page content, a cookie you'll need to send back.
If you use ASIHTTPRequest to perform the requests and use the same instance of the object to make subsequent requests, it will take care of sending those revised cookies each time. I love this library and recommend it.
http://allseeing-i.com/ASIHTTPRequest/
If instead you're using an NSURLConnection and prefer to manage the cookies yourself, the NSHTTPCookie object will help.

asp.net mvc 2 -- losing authorization when RedirectToAction with JSON data

I'm refactoring some MVC code that originally used POST'ed form data. The form's fields are serialized using jquery's serialize() method and sent to an MVC controller Save Action that checks things out and redirects as appropriate (if errors in form values, redirect to the Edit Action, if fine then save and redirect to the Display Action). All actions are invoked via AJAX and return Partial Views. Everything works grand. Note: The site uses AD-based authorization, so users are prompted for their windows credentials upon first loading the site, but are never prompted again.
However, I'm now looking to interact with the server via JSON objects instead of form fields. Granted, I serialize the JSON object on the client and, with the aid of an imported MVC2 Futures/MVC3 class JsonValueProviderFactory, am able to correctly model bind the sent JSON object to a C# class in the Controller's parameters.
I maintain the same logic, but things start to blow up when I try to return a RedirectToAction ActionResult when the Controller accepts JSON objects. I lose authentication, the user is prompted for their credentials again, and I find myself in a infinite loop on the originally requested Action (save). Every time the user is prompted for credentials and simply runs through the Save Action again. The end result for the user is an unending alerts prompting for login credentials. Neither of the actions specified in the RedirectToAction calls are ever hit.
Can the fact that the original request uses a JSON contentType be interfering with the behavior of RedirectToAction? That's the only thing I can think of as it works fine when I don't use JSON to post and it works fine when I return PartialViews instead of using RedirectToAction. The infinite repeat of the Controller Action and continual loss of authorization credentials seems to suggest that RedirectToAction is not the way to go in this situation.
I can post code on request. I am also successfully handling stuff like copying the ModelState over to TempData and other RedirectToAction tricks. Again, it DOES work when using a non-JSON solution. Any insight is greatly appreciated!!
EDIT WITH FOLLOW-UP INFO:
Turns out, I get an "Unauthorized" error even when I completely disable NTLM authentication/authorization for the site. IIS server doesn't look for any authorization, web site doesn't look for any authorization, yet the error when trying to Redirect with JSON contentType request still occurs and complains of being "Unauthorized". This is WEIRD.
To update everyone, I haven't found a solution nor do I know for-sure what the situation is. However, I'm willing to bet it has to do with the fact that RedirectToAction issues http GET requests and the action I'm redirecting to only accepts POSTs. Even if I remove the restriction, it's still sending JSON data and it still needs to be done by POST.
In short, RedirectToAction with JSON data appears to be fundamentally undoable. You need to POST JSON data but RedirectToAction emits GET requests. That's my going theory, at least. =)

Request.IsAuthenticated = false on Ajax post

I am using the jQuery plugin to add support for SwfUpload by steven sanderson which allows files to be uploaded with ajax.
The problem is that Request.IsAuthenticated is always false with an ajax post. This means that User.Identity.Name = "" which doesn't allow me to load up values I need to save the file.
Is this by design and what is best practice?
EDIT: The request is authenticated when the page loads but only on the ajax post is it no longer authenticated. Other ajax calls are also authenticated properly.
Assuming that you are using forms authentication, I think the problem is that the swfUpload utility, which uses flash, isn't dragging along the proper authentication cookies for the site back to the server with it's post. You would have to go find out how to get the flash to bring the auth cookies back to the server with it's requests.
quick look:
http://www.google.com/search?hl=en&safe=off&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&hs=pr3&q=swfupload+authentication+cookies&aq=f&oq=&aqi=

Make ajax get redirect main page to login when auth times out

I'm using ASP.Net MVC beta 1 and I'm using the asp.net membership provider with the standard authentication controller to restrict access to my site.
I'm using ajax functionality to provide e.g. editing of values by loading partial views into a div with either jQuery $.get/$.ajax or with the Ajax.Actionlink MVC helper. This all works fine most of the time.
My problem comes once the login times out and you click on one of the ajax edit links - the ajax call returns the login page which is put into the div normally used for the edit form.
I want to find a way to redirect the whole page to the login form, when the authentication has timed out and an ajax link is clicked.
One way I can think of is looking at the html returned from the ajax call in the response callback and searching for the 'login' text or form field and doing a redirect from there - but this doesn't feel very clean - is there a better way?
This might help some:
Bypass Forms Authentication auto redirect to login, How to?
From the above answer it looks like http 403 isn't intercepted by Forms Authentication, so you can roll your own ActionFilter that returns an http 403 response if its an Ajax Request and Authorization failed.
On the client side, you could then check the response code for 403, and redirect to the appropriate login url.
There are probably other ways to do this as well!

Resources