gpt4 book ai didi

javascript - antiforgeryToken 放在哪里

转载 作者:数据小太阳 更新时间:2023-10-29 06:11:39 25 4
gpt4 key购买 nike

我有一个带有 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">

在我的 Angular View (加载到布局页面的 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};
}

因此,无论我将 token 放在哪里,无论我将什么用于“内容类型”(我尝试了 application-json 和 www-form-urlencoded),我总是会收到错误消息“所需的防伪表单字段” __RequestVerificationToken“不存在。”

我什至尝试命名 __RequestVerificationToken 和 RequestVerificationToken

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

我还查看了几个链接,这些链接要求您实现自己的 AntiForgeryToeknVerifyAttrbute 并验证作为 cookieToken:formToken 发送的 token ,我没有尝试过,但为什么我无法让它工作,而这适用于MVC Controller (非 Angular 柱)

最佳答案

是的。默认情况下,MVC 框架将检查 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);
}

您需要创建自己的过滤器以从 Request.Header 中检查它

Code Snippet from Phil Haack's Article -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
}

在这里查看 MVC 4 implementation , 以避免 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"]);
}
}

关于javascript - antiforgeryToken 放在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22780958/

25 4 0