Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This question brings up an interesting discussion.</p> <p>Provided that the request Content-Type is <code>application/json</code>, then CSRF is not a concern. This is because application/json requests must be submitted via <code>XmlHttpRequest</code>, and the cookie which is a necessary part of the verification of your AntiForgeryToken cannot be passed cross-site, but must adhere to the <a href="http://en.wikipedia.org/wiki/Same_origin_policy" rel="noreferrer">Same Origin Policy</a>.</p> <p><strong>However,</strong> it is possible for a malicious user to submit a request via <code>application/x-www-form-urlencoded</code> which contains the information which will appear to be a valid JSON request, and which will pass any authorization cookies back to your application. There is a more detailed discussion of this at <a href="http://forums.asp.net/t/1624454.aspx/1?MVC3+JSON+Model+binding+not+working+with+AntiForgery" rel="noreferrer">http://forums.asp.net/t/1624454.aspx/1?MVC3+JSON+Model+binding+not+working+with+AntiForgery</a> and at <a href="http://aspnet.codeplex.com/workitem/7472" rel="noreferrer">http://aspnet.codeplex.com/workitem/7472</a>, where I post a proof-of-concept.</p> <p>While it is possible to include the __RequestVerificationToken in a JSON request, a better line of defense is to create an Attribute to verify that a request is of type <code>application/json</code>, since any other request being submitted to your action which expects JSON is in fact invalid, and should not be handled.</p> <p>I expect that this security issue will be addressed in MVC 4.</p> <p><strong>UPDATE:</strong></p> <p>Here is a simple <code>AuthorizeAttribute</code> class you can use to decorate any actions which expect to receive JSON:</p> <pre><code>public class JsonRequestAttribute : AuthorizeAttribute { /* * * CONFIRM that this is REALLY a JSON request. * This will mitigate the risk of a CSRF attack * which masquerades an "application/x-www-form-urlencoded" request * as a JSON request * */ public override void OnAuthorization(AuthorizationContext filterContext) { if (!filterContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) { // This request is masquerading as a JSON request, kill it. JsonResult unauthorizedResult = new JsonResult(); unauthorizedResult.Data = "Invalid request"; unauthorizedResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet; filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; filterContext.Result = unauthorizedResult; } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload