使用AngularJS中的自定义属性发布和验证MVC CSRF令牌不起作用

时间:2016-11-15 09:24:16

标签: angularjs asp.net-mvc csrf actionfilterattribute filterattribute

我正在使用Angular JS和ASP.NET MVC开发Web应用程序。我在验证CSRF令牌时遇到问题。我问了一个处理CSRF令牌和AngularJS的问题。但这个问题有点不同。我现在正在关注此链接 - http://techbrij.com/angularjs-antiforgerytoken-asp-net-mvc

我创建了一个像这样的自定义CSRF验证类

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class AngularValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
    private void ValidateRequestHeader(HttpRequestBase request)
    {
        string cookieToken = String.Empty;
        string formToken = String.Empty;
        string tokenValue = request.Headers["RequestVerificationToken"];
        if (!String.IsNullOrEmpty(tokenValue))
        {
            string[] tokens = tokenValue.Split(':');
            if (tokens.Length == 2)
            {
                cookieToken = tokens[0].Trim();
                formToken = tokens[1].Trim();
            }
        }
        AntiForgery.Validate(cookieToken, formToken);
    }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        try
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                ValidateRequestHeader(filterContext.HttpContext.Request);
            }
            else
            {
                AntiForgery.Validate();
            }
        }
        catch (HttpAntiForgeryException e)
        {
            throw new HttpAntiForgeryException("Anti forgery token cookie not found"); // This line is throwing error
        }
    }           
}

然后我在AngularJS中这样发帖:

$http({
    method: 'POST',
    url: path,
    data: { Email : $scope.email, Password : $scope.password },
    headers: {
        'RequestVerificationToken': $rootScope.csrfToken
    }
}).success(function (data, status, headers, config) {
    alert('success')
}).error(function (data, status, headers, config) {
    alert('error')
});

它总是抛出此错误

enter image description here

我在上面的代码中评论了错误。我的代码出了什么问题?

0 个答案:

没有答案