防伪令牌+ Web API( - MVC)

Jai*_*der 11 antiforgerytoken asp.net-web-api

如何在没有ASP.NET MVC的情况下使用带有ASP.NET Web API的Anti-Forgery Token?

Stephen Walther在http://stephenwalther.com/archive/2013/03/05/security-issues-with-single-page-apps上发表了"使用ASP.NET MVC防止跨站点请求伪造攻击"的文章.但是他的解决方案包括MVC/Razor,在我的前端我不打算包含它.并且有很多类似的文章,解决方案正在添加,@Html.AntiForgeryToken()但这不是我的解决方案.

后来,我解决了另一个问题,"同源政策":http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api,这可能是防止CSRF的解决方案?我不这么认为.

Sli*_*Sim 3

我的问题是我不想使用 MVC,只想提供由 WebApi 支持的静态 html 文件。这是我所做的(这可行吗?)创建一个 Http 模块,在提供任何静态文件时设置随机 cookie 值。例如:

public class XSRFModule : IHttpModule {
    ...

    void context_EndRequest(object sender, EventArgs e) {
        if (Path.GetExtension(HttpContext.Current.Request.Path) == ".html") {
            HttpContext.Current.Response.Cookies.Add(new HttpCookie("XSRF-TOKEN", Guid.NewGuid().ToString()));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的 html 页面中,在调用 api 时使用 javascript 将 cookie 值添加到标头:

function callApi() {
        xhr = new XMLHttpRequest();
        xhr.open("GET", "api/data", true);
        var regex = /\b(?:XSRF-TOKEN=)(.*?)(?=\s|$)/
        var match = regex.exec(document.cookie);
        xhr.setRequestHeader("X-XSRF-TOKEN", match[1]);
        xhr.send();
    }
Run Code Online (Sandbox Code Playgroud)

最后,在您的 中HttpModule,在处理对 api 的任何调用之前检查 cookie 是否与标头匹配:

void context_BeginRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.Request.Path.StartsWith("/api"))
        {
            string fromCookie = HttpContext.Current.Request.Cookies.Get("XSRF-TOKEN").Value;
            string fromHeader = HttpContext.Current.Request.Headers["X-XSRF-TOKEN"];
            if (fromCookie != fromHeader)
            {
                HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                HttpContext.Current.Response.End();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

您需要将HttpOnly标志设置为FALSE,以便您域中的 javascript 可以读取 cookie 并设置标头。我不是安全专家,因此我希望社区其他成员对此解决方案提供一些反馈。

编辑

如果您使用 OWIN,则可以使用全局操作过滤器以及中间件插件:

启动.cs

app.UseStaticFiles(new StaticFileOptions {
            OnPrepareResponse = (responseContext) => {
                responseContext.OwinContext.Response.Cookies.Append("XSRF-TOKEN", Guid.NewGuid().ToString());
            },
            FileSystem = "wwwroot"
        });
Run Code Online (Sandbox Code Playgroud)

XsrfFilter.cs

public class XsrfFilter : ActionFilterAttribute {
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) {

        string fromCookie = actionContext.Request.Headers.GetCookies("XSRF-TOKEN").FirstOrDefault()["XSRF-TOKEN"].Value;
        string fromHeader = actionContext.Request.Headers.GetValues("X-XSRF-TOKEN").FirstOrDefault();

        if (fromCookie == fromHeader) return;

        actionContext.Response = new HttpResponseMessage(HttpStatusCode.OK);
        actionContext.Response.ReasonPhrase = "bad request";
    }
}
Run Code Online (Sandbox Code Playgroud)