zoukankan      html  css  js  c++  java
  • Preventing CSRF With Ajax

    https://stackoverflow.com/a/24394578/3782855

    You don't need the ValidationHttpRequestWrapper solution since MVC 4. According to this link.

    1. Put the token in the headers.
    2. Create a filter.
    3. Put the attribute on your method.

    Here is my solution:

    var token = $('input[name="__RequestVerificationToken"]').val();
    var headers = {};
    headers['__RequestVerificationToken'] = token;
    $.ajax({
        type: 'POST',
        url: '/MyTestMethod',
        contentType: 'application/json; charset=utf-8',
        headers: headers,
        data: JSON.stringify({
            Test: 'test'
        }),
        dataType: "json",
        success: function () {},
        error: function (xhr) {}
    });
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
    
            var httpContext = filterContext.HttpContext;
            var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName];
            AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]);
        }
    }
    
    
    [HttpPost]
    [AllowAnonymous]
    [ValidateJsonAntiForgeryToken]
    public async Task<JsonResult> MyTestMethod(string Test)
    {
        return Json(true);
    }

    Updated Anti-XSRF Validation for ASP.NET MVC 4 RC

    Preventing CSRF With Ajax

    You can try to apply the ValidateAntiForgeryTokenAttribute attribute to an action method, but it will fail every time if you try to post JSON encoded data to the action method. On one hand, the most secure action possible is one that rejects every request. On the other hand, that’s a lousy user experience.

    The problem lies in the fact that the under the hood, deep within the call stack, the attribute peeks into the Request.Form collection to grab the anti-forgery token. But when you post JSON encoded data, there is no form collection to speak of. We hope to fix this at some point and with a more flexible set of anti-forgery helpers. But for the moment, we’re stuck with this.

       

  • 相关阅读:
    poj 1475 Pushing Boxes 推箱子(双bfs)
    poj 1806 Frequent values(RMQ 统计次数) 详细讲解
    poj 2846 Repository
    poj Ping pong LA 4329 (树状数组统计数目)
    POJ 1962-Corporative Network (并查集)
    hdu 2217 Visit
    nyoj304 节能
    与R纠缠的两件事——rownames和子集--转载
    七步精通Python机器学习--转载
    win10专业版激活(亲测可用)
  • 原文地址:https://www.cnblogs.com/chucklu/p/11649821.html
Copyright © 2011-2022 走看看