【问题标题】:CSRF on singlepage using Web Api 2 backend使用 Web Api 2 后端的单页 CSRF
【发布时间】:2016-08-16 23:32:13
【问题描述】:

我正在尝试在单页应用程序上使用 .Net Framework 中的 AntiForgeryToken 实现 CSRF。我在 .csthml 文件中实现了一些代码,并创建了 AuthorizeAttribute:

Index.cshtml

<script>

    @functions{
        public string GetAntiForgeryToken()
        {
            string cookieToken, formToken;
            System.Web.Helpers.AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return cookieToken + ":" + formToken;                
        }
    }

    $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
        var xxx = '@GetAntiForgeryToken()';
        jqXHR.setRequestHeader("X-CSRF", xxx);
    });

</script>

ValidateHttpAntiForgeryTokenAttribute.cs

public class ValidateHttpAntiForgeryTokenAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        var headers = actionContext.Request.Headers;

        var headerToken = headers.Contains("X-CSRF") ? headers.GetValues("X-CSRF").FirstOrDefault() : null;

        if (headerToken == null)
        {
            return false;
        }

        var tokenValues = headerToken.Split(':');

        if (tokenValues.Length < 2)
        {
            return false;
        }
        else
        {
            var cookieToken = tokenValues[0];
            var formToken = tokenValues[1];
            try
            {
                AntiForgery.Validate(cookieToken, formToken);
            }
            catch(Exception ex)
            {
                return false;
            }
        }           
        return base.IsAuthorized(actionContext);
    }
}         

MyController.cs

    [HttpGet]
    [ValidateHttpAntiForgeryTokenAttribute]
    public HttpResponseMessage Get()
    {
     ...
    }

每次调用 ValidateHttpAntiForgeryTokenAttribute 时,都会出现以下错误:

The provided anti-forgery token was meant for user "CMP\usr", but the current user is "dev@company.net"

我想知道为什么它显示计算机的用户名而不是登录应用程序的用户名,以及为什么执行调用 GetAntiForgeryToken() 时令牌没有改变。

提前致谢。

【问题讨论】:

标签: c# antiforgerytoken


【解决方案1】:

作为快速修复(如果您不关心反 CSRF 逻辑中的用户名验证)将是:

AntiForgeryConfig.SuppressIdentityHeuristicChecks = true

AppStart 逻辑中的某处 (global.asax)。

【讨论】:

  • 还是同样的问题
  • AntiForgeryConfig 不为我提供SuppressIdentityHeuristicChecks
  • 这不会阻止问题中的异常,该异常在验证期间发生,因为令牌包含与当前身份不同的用户名。 SuppressIdentityHeuristicChecks 只是要求用户名、声明或附加数据 (github.com/mono/aspnetwebstack/blob/6248bfd24c/src/…),并在生成令牌期间引发异常。没有它,用户名(如果可用)在生成时仍将设置在“表单”令牌上,并在下一次请求时验证。
  • 查看此答案的更新:stackoverflow.com/a/15615786
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 2012-06-22
  • 2015-12-04
  • 2018-01-19
  • 2014-10-11
  • 1970-01-01
  • 2017-06-11
相关资源
最近更新 更多