防伪手段适用于用户“ MyUserName”,但当前用户为“”以进行Windows身份验证

时间:2018-07-16 17:04:03

标签: asp.net model-view-controller csrf

我有一个启用Windows身份验证的现有MVC网站。该网站有一个自定义模块。身份验证模式为Windows,授权在自定义操作过滤器中完成。现在我的代码有以下问题-

  1. 代码的意义是什么,因为MVC默认方法也用于POST视图中。要验证所有GET请求?

  2. 调用AntiForgery.Validate()时,它将引发错误反伪造的含义对于用户“ MyUserName”,但当前用户为“”。但是,当我刷新页面时,它可以工作。

  3. 对引荐网址!= null的检查在我看来并不好,因为它将始终对第一个Get请求抛出错误。

AntiForgeryModule.cs

public class AntiForgeryModule : IHttpModule
{
    private const string ForgeryToken = "AFT";

    public void Init(HttpApplication context)
    {
        context.BeginRequest += Context_BeginRequest;
        context.EndRequest += Context_EndRequest;
    }

    private void Context_EndRequest(object sender, EventArgs e)
    {
        HttpContext context = (sender as HttpApplication).Context;

        CreateCookieTokens(context);
    }

    private void CreateCookieTokens(HttpContext context)
    {
        if (context.Response.ContentType.Contains("text/html"))
        {
            string headerToken = string.Empty;
            string trailerToken = string.Empty;

            AntiForgery.GetTokens(null, out headerToken, out trailerToken);
            HttpCookie cookie = new HttpCookie(ForgeryToken);

            cookie.Value = headerToken + ":" + trailerToken;
            cookie.Expires = DateTime.Now.AddMinutes(20);

            context.Response.Cookies.Add(cookie);
        }
    }

    private void Context_BeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = sender as HttpApplication;
        HttpContext context = app.Context;
        HttpRequest request = context.Request;

        if (request.RequestType.Equals("GET") && request.AcceptTypes.Contains("text/html"))
        {
            if (request.Cookies != null && request.Cookies[ForgeryToken] != null)
            {
                if (request.UrlReferrer != null)
                {
                    if (request.UrlReferrer.Host.Equals(request.Url.Host))
                    {
                        HttpCookie cookie = request.Cookies[ForgeryToken];
                        string[] cookies = cookie.Value.Split(':');

                        string headerToken = string.Empty;
                        string trailerToken = string.Empty;

                        headerToken = cookies[0];
                        trailerToken = cookies[1];

                        AntiForgery.Validate(headerToken, trailerToken);
                    }
                    else
                    {
                        //ThrowError
                    }
                }
                else
                {
                    //ThrowError
                }
            }
        }
    }
}

0 个答案:

没有答案