使用MVC 4 RC为Web API实现ValidatingAntiForgeryToken属性的问题

时间:2012-07-30 16:49:55

标签: asp.net-mvc-4 asp.net-web-api antiforgerytoken

我正在制作基于JSON的AJAX请求,并且MVC控制器非常感谢Phil Haack的Preventing CSRF with AJAX和Johan Driessen的Updated Anti-XSRF for MVC 4 RC。但是,当我将以API为中心的控制器转换为Web API时,我遇到的问题是两种方法之间的功能明显不同,而且我无法转换CSRF代码。

ScottS最近提出了一个类似的question,由Darin Dimitrov提出answered。 Darin的解决方案涉及实现一个调用AntiForgery.Validate的授权过滤器。不幸的是,这段代码对我不起作用(参见下一段),老实说 - 对我来说太先进了。

据我了解,Phil的解决方案在没有表单元素的情况下制作JSON请求时克服了MVC AntiForgery的问题;表单元素由AntiForgery.Validate方法假定/预期。我相信这可能就是为什么我也遇到Darin解决方案的问题。我收到一个HttpAntiForgeryException“所需的防伪表单字段'__RequestVerificationToken'不存在”。我确定令牌正在被POST(尽管在Phil Haack的解决方案的标题中)。这是客户电话的快照:

$token = $('input[name=""__RequestVerificationToken""]').val();
$.ajax({
    url:/api/states",
    type: "POST",
    dataType: "json",
    contentType: "application/json: charset=utf-8",
    headers: { __RequestVerificationToken: $token }
}).done(function (json) {
    ...
});

我尝试通过将Johan的解决方案与Darin's混合在一起来实现攻击,并且能够使事情正常工作但是我正在介绍HttpContext.Current,不确定这是否合适/安全以及为什么我不能使用提供的HttpActionContext。

这是我不雅的混搭......改变是试块中的2行:

public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
    try
    {
        var cookie = HttpContext.Current.Request.Cookies[AntiForgeryConfig.CookieName];
        AntiForgery.Validate(cookie != null ? cookie.Value : null, HttpContext.Current.Request.Headers["__RequestVerificationToken"]);
    }
    catch
    {
        actionContext.Response = new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.Forbidden,
            RequestMessage = actionContext.ControllerContext.Request
        };
        return FromResult(actionContext.Response);
    }
    return continuation();
}

我的问题是:

  • 我是否认为Darin的解决方案假设存在表单元素?
  • 使用Johan的MVC 4 RC代码将Darin的Web API过滤器混合在一起的优雅方法是什么?

提前致谢!

5 个答案:

答案 0 :(得分:32)

您可以尝试从标题中读取:

var headers = actionContext.Request.Headers;
var cookie = headers
    .GetCookies()
    .Select(c => c[AntiForgeryConfig.CookieName])
    .FirstOrDefault();
var rvt = headers.GetValues("__RequestVerificationToken").FirstOrDefault();
AntiForgery.Validate(cookie != null ? cookie.Value : null, rvt);

注意:GetCookies是类HttpRequestHeadersExtensions中存在的扩展方法,它是System.Net.Http.Formatting.dll的一部分。它很可能存在于C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Net.Http.Formatting.dll

答案 1 :(得分:13)

只是想补充一点,这种方法也适用于我(.ajax将JSON发布到Web API端点),尽管我通过继承ActionFilterAttribute并重写OnActionExecuting方法来简化它。

public class ValidateJsonAntiForgeryTokenAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        try
        {
            var cookieName = AntiForgeryConfig.CookieName;
            var headers = actionContext.Request.Headers;
            var cookie = headers
                .GetCookies()
                .Select(c => c[AntiForgeryConfig.CookieName])
                .FirstOrDefault();
            var rvt = headers.GetValues("__RequestVerificationToken").FirstOrDefault();
            AntiForgery.Validate(cookie != null ? cookie.Value : null, rvt);
        }
        catch
        {               
            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Unauthorized request.");
        }
    }
}

答案 2 :(得分:0)

使用Darin的答案的扩展方法,检查是否存在标题。检查意味着产生的错误消息更能说明错误(“所需的防伪形式字段”__RequestVerificationToken“不存在。”)与“找不到给定的标题。”

public static bool IsHeaderAntiForgeryTokenValid(this HttpRequestMessage request)
{
    try
    {
        HttpRequestHeaders headers = request.Headers;
        CookieState cookie = headers
                .GetCookies()
                .Select(c => c[AntiForgeryConfig.CookieName])
                .FirstOrDefault();

        var rvt = string.Empty;
        if (headers.Any(x => x.Key == AntiForgeryConfig.CookieName))
            rvt = headers.GetValues(AntiForgeryConfig.CookieName).FirstOrDefault();

        AntiForgery.Validate(cookie != null ? cookie.Value : null, rvt);
    }
    catch (Exception ex)
    {
        LogHelper.LogError(ex);
        return false;
    }

    return true;
}

ApiController用法:

public IHttpActionResult Get()
{
    if (Request.IsHeaderAntiForgeryTokenValid())
        return Ok();
    else
        return BadRequest();
}

答案 3 :(得分:0)

使用AuthorizeAttribute的实现:

using System;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Helpers;
using System.Web.Http;
using System.Web.Http.Controllers;

  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
  public class ApiValidateAntiForgeryToken : AuthorizeAttribute {
    public const string HeaderName = "X-RequestVerificationToken";

    private static string CookieName => AntiForgeryConfig.CookieName;

    public static string GenerateAntiForgeryTokenForHeader(HttpContext httpContext) {
      if (httpContext == null) {
        throw new ArgumentNullException(nameof(httpContext));
      }

      // check that if the cookie is set to require ssl then we must be using it
      if (AntiForgeryConfig.RequireSsl && !httpContext.Request.IsSecureConnection) {
        throw new InvalidOperationException("Cannot generate an Anti Forgery Token for a non secure context");
      }

      // try to find the old cookie token
      string oldCookieToken = null;
      try {
        var token = httpContext.Request.Cookies[CookieName];
        if (!string.IsNullOrEmpty(token?.Value)) {
          oldCookieToken = token.Value;
        }
      }
      catch {
        // do nothing
      }

      string cookieToken, formToken;
      AntiForgery.GetTokens(oldCookieToken, out cookieToken, out formToken);

      // set the cookie on the response if we got a new one
      if (cookieToken != null) {
        var cookie = new HttpCookie(CookieName, cookieToken) {
          HttpOnly = true,
        };
        // note: don't set it directly since the default value is automatically populated from the <httpCookies> config element
        if (AntiForgeryConfig.RequireSsl) {
          cookie.Secure = AntiForgeryConfig.RequireSsl;
        }
        httpContext.Response.Cookies.Set(cookie);
      }

      return formToken;
    }


    protected override bool IsAuthorized(HttpActionContext actionContext) {
      if (HttpContext.Current == null) {
        // we need a context to be able to use AntiForgery
        return false;
      }

      var headers = actionContext.Request.Headers;
      var cookies = headers.GetCookies();

      // check that if the cookie is set to require ssl then we must honor it
      if (AntiForgeryConfig.RequireSsl && !HttpContext.Current.Request.IsSecureConnection) {
        return false;
      }

      try {
        string cookieToken = cookies.Select(c => c[CookieName]).FirstOrDefault()?.Value?.Trim(); // this throws if the cookie does not exist
        string formToken = headers.GetValues(HeaderName).FirstOrDefault()?.Trim();

        if (string.IsNullOrEmpty(cookieToken) || string.IsNullOrEmpty(formToken)) {
          return false;
        }

        AntiForgery.Validate(cookieToken, formToken);
        return base.IsAuthorized(actionContext);
      }
      catch {
        return false;
      }
    }
  }

然后用[ApiValidateAntiForgeryToken]装饰您的控制器或方法

并添加到剃刀文件中以生成javascript的令牌:

<script>
var antiForgeryToken = '@ApiValidateAntiForgeryToken.GenerateAntiForgeryTokenForHeader(HttpContext.Current)';
// your code here that uses such token, basically setting it as a 'X-RequestVerificationToken' header for any AJAX calls
</script>

答案 4 :(得分:0)

如果对.net核心有帮助,则标头的默认值实际上只是“ RequestVerificationToken”,而没有“ __”。因此,如果将标头的密钥更改为此,它将起作用。

如果愿意,您还可以覆盖标题名称:

services.AddAntiforgery(o => o.HeaderName = "__RequestVerificationToken")