Anti Forgery验证不起作用

时间:2013-10-23 05:52:10

标签: asp.net asp.net-mvc antiforgerytoken

我知道我错过了某些东西,但它没有用,我不知道出了什么问题。这是自定义Anti伪造属性。

[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>

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

2 个答案:

答案 0 :(得分:0)

您没有__RequestVerificationToken请求标头,这是您在此处尝试阅读的内容:

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

您要发送的实际标头名为Authorization。因此,您可以使用将发送令牌值的专用标头:

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

然后:

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

答案 1 :(得分:0)

为什么不使用默认框架防伪动作过滤器和相对Html Helper? 不要反对框架:)

有关CSRF here

的更多信息
相关问题