究竟要把防伪手表放在哪里

ind*_*imp 5 javascript asp.net-mvc http http-headers angularjs

我有一个布局页面,其中包含一个带有AntiForgeryToken的表单

using (Html.BeginForm(action, "Account", new { ReturnUrl = returnUrl }, FormMethod.Post, new { Id = "xcrf-form" }))
Run Code Online (Sandbox Code Playgroud)

这会生成一个隐藏字段

<input name="__RequestVerificationToken" type="hidden" value="p43bTJU6xjctQ-ETI7T0e_0lJX4UsbTz_IUjQjWddsu29Nx_UE5rcdOONiDhFcdjan88ngBe5_ZQbHTBieB2vVXgNJGNmfQpOm5ATPbifYE1">
Run Code Online (Sandbox Code Playgroud)

在我的角度视图中(在布局页面中加载div,我这样做

<form class="form" role="form" ng-submit="postReview()">
Run Code Online (Sandbox Code Playgroud)

我的postReview()代码如下

$scope.postReview = function () {
    var token = $('[name=__RequestVerificationToken]').val();

    var config = {
        headers: {
            "Content-Type": "multipart/form-data",
            // the following when uncommented does not work either
            //'RequestVerificationToken' : token
            //"X-XSRF-TOKEN" : token
        }
    }

    // tried the following, since my other MVC controllers (non-angular) send the token as part of form data, this did not work though
    $scope.reviewModel.__RequestVerificationToken = token;

    // the following was mentioned in some link I found, this does not work either
    $http.defaults.headers.common['__RequestVerificationToken'] = token;

    $http.post('/Review/Create', $scope.reviewModel, config)
    .then(function (result) {
        // Success
        alert(result.data);
    }, function (error) {
        // Failure
        alert("Failed");
    });
}
Run Code Online (Sandbox Code Playgroud)

我的MVC Create方法如下

    [HttpPost]
    [ValidateAntiForgeryToken]
    [AllowAnonymous]
    public ActionResult Create([Bind(Include = "Id,CommentText,Vote")] ReviewModel reviewModel)
    {
        if (User.Identity.IsAuthenticated == false)
        {
            // I am doing this instead of [Authorize] because I dont want 302, which browser handles and I cant do client re-direction
            return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
        }

        // just for experimenting I have not yet added it to db, and simply returning
        return new JsonResult {Data = reviewModel, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
    }
Run Code Online (Sandbox Code Playgroud)

所以无论我在哪里放置令牌,无论我使用什么'Content-Type'(我尝试过application-json和www-form-urlencoded)我总是得到错误"所需的防伪表单字段"__RequestVerificationToken"是不存在."

我甚至试过命名__RequestVerificationToken和RequestVerificationToken

为什么我的服务器找不到该死的令牌?

我还看了几个链接,要求你实现自己的AntiForgeryToeknVerifyAttrbute并验证作为cookieToken发送的令牌:formToken,我没有尝试过,但为什么我无法让它工作,而这适用于MVC控制器(无角度的帖子)

Mur*_*san 5

是.默认情况下,MVC Framework将检查Request.Form["__RequestVerificationToken"].

检查 MVC source code

    public AntiForgeryToken GetFormToken(HttpContextBase httpContext)
    {
        string value = httpContext.Request.Form[_config.FormFieldName];
        if (String.IsNullOrEmpty(value))
        {
            // did not exist
            return null;
        }

        return _serializer.Deserialize(value);
    }
Run Code Online (Sandbox Code Playgroud)

您需要创建自己的过滤器以进行检查 Request.Header

Phil Haack的文章 - MVC 3的代码片段

private class JsonAntiForgeryHttpContextWrapper : HttpContextWrapper {
  readonly HttpRequestBase _request;
  public JsonAntiForgeryHttpContextWrapper(HttpContext httpContext)
    : base(httpContext) {
    _request = new JsonAntiForgeryHttpRequestWrapper(httpContext.Request);
  }

  public override HttpRequestBase Request {
    get {
      return _request;
    }
  }
}

private class JsonAntiForgeryHttpRequestWrapper : HttpRequestWrapper {
  readonly NameValueCollection _form;

  public JsonAntiForgeryHttpRequestWrapper(HttpRequest request)
    : base(request) {
    _form = new NameValueCollection(request.Form);
    if (request.Headers["__RequestVerificationToken"] != null) {
      _form["__RequestVerificationToken"] 
        = request.Headers["__RequestVerificationToken"];
    }
}

  public override NameValueCollection Form {
    get {
      return _form;
    }
  }
}

[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 = new JsonAntiForgeryHttpContextWrapper(HttpContext.Current);
    AntiForgery.Validate(httpContext, Salt ?? string.Empty);
  }

  public string Salt {
    get;
    set;
  }

  // The private context classes go here
}
Run Code Online (Sandbox Code Playgroud)

请查看此处的MVC 4实现,以避免出现salt问题

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class,
                AllowMultiple = false, Inherited = true)]
public sealed 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"]);
    }
}
Run Code Online (Sandbox Code Playgroud)