我有了與AntiForgeryToken形式到底在哪把antiforgeryToken
using (Html.BeginForm(action, "Account", new { ReturnUrl = returnUrl }, FormMethod.Post, new { Id = "xcrf-form" }))
這生成一個隱藏字段
<input name="__RequestVerificationToken" type="hidden" value="p43bTJU6xjctQ-ETI7T0e_0lJX4UsbTz_IUjQjWddsu29Nx_UE5rcdOONiDhFcdjan88ngBe5_ZQbHTBieB2vVXgNJGNmfQpOm5ATPbifYE1">
在我的角度視圖(即裝在一個div佈局頁面在佈局網頁,我這樣做
<form class="form" role="form" ng-submit="postReview()">
而且我對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");
});
}
我的MVC創建方法如下
[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};
}
所以無論身在何處,我把道理,不管我用「的Content-Type」(我試過應用JSON和WWW-窗體-urlencoded)我總是得到錯誤「所要求的防僞表單字段" __RequestVerificationToken "不存在。」
我甚至嘗試命名__RequestVerificationToken和RequestVerificationToken
爲什麼我的服務器沒有找到該死的令牌?
我還查看了一些鏈接,要求您實現自己的AntiForgeryToeknVerifyAttrbute並驗證以cookieToken形式發送的令牌:formToken,我沒有嘗試過,但爲什麼我無法讓它工作,而這適用於MVC控制器(非角柱)
感謝您的回答,根據你說什麼,我決定把令牌形式本身要做到這一點,我需要按照http://stackoverflow.com/a/14868725/2475810 – indichimp