0

我知道我错过了一些东西,但它不起作用,我不知道出了什么问题。这是自定义的防伪属性。

[AttributeUsage(AttributeTargets.Class)]
public class ValidateAntiForgeryTokenOnAllPosts : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        var request = filterContext.HttpContext.Request;

        //  Only validate POSTs
        if (request.HttpMethod == WebRequestMethods.Http.Post)
        {
            //  Ajax POSTs and normal form posts have to be treated differently when it comes
            //  to validating the AntiForgeryToken
            if (request.IsAjaxRequest())
            {
                var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];

                var cookieValue = antiForgeryCookie != null
                    ? antiForgeryCookie.Value
                    : null;

                AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);
            }
            else
            {
                new ValidateAntiForgeryTokenAttribute()
                    .OnAuthorization(filterContext);
            }
        }
    }
}

我正在从 ajax 请求发送令牌。

console.log(JSON.stringify(data));
    return $.ajax({
        url: url,
        type: "post",
        cache: false,
        contentType: "application/JSON; charset=utf-8",
        crossDomain: true,
        data: JSON.stringify(data),
        dataType: "json",
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Accept", "application/json, text/json, */*");
            xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
            xhr.setRequestHeader("Authorization", "__RequestVerificationToken token=\"FuHCLyY46\"");
        }

在 Asp Master Page 中,我放置了隐藏字段。

<form id="form1" runat="server">

<div>
    <input type="hidden" name="__RequestVerificationToken" value="FuHCLyY46"/>

</div>

</form>

但它不起作用。请确定我在做什么错?

4

2 回答 2

0

为什么不使用默认框架的防伪操作过滤器和相关的 Html Helper?不要与框架作斗争:)

更多关于 CSRF的信息在这里

于 2013-10-23T07:17:55.070 回答
0

您没有__RequestVerificationToken在此处尝试阅读的请求标头:

AntiForgery.Validate(cookieValue, request.Headers["__RequestVerificationToken"]);

您发送的实际标头称为Authorization. 因此,您可以使用一个专用的标头来发送令牌值:

xhr.setRequestHeader("AntiForgeryToken", "FuHCLyY46");

接着:

AntiForgery.Validate(cookieValue, request.Headers["AntiForgeryToken"]);
于 2013-10-23T07:01:21.253 回答