在 IAuthenticationFilter 的 HttpUnauthorizedResult 之后检索 Windows 身份

Retrieve Windows Identity after HttpUnauthorizedResult for IAuthenticationFilter

我有一个 IAuthenticationFilter 将检查 SharePoint 中的用户组:

public class BasicAuthFilter : ActionFilterAttribute, IAuthenticationFilter
    {
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            string userLoginName = filterContext.RequestContext.HttpContext.User.Identity.Name;
            if (SecurityManager.Auth(userLoginName))
                return;
            else
                filterContext.Result = new RedirectResult(new UrlHelper(filterContext.RequestContext).Action("AccessDenied", "Error"));
        }

        ...
    }
}

它将 运行 处理每个请求,但 ErrorController

除外
[AllowAnonymous]
public class ErrorController : Controller
    ...

    // Display view and link for "Logout"
    public ActionResult AccessDenied()
    {
        return View();
    }

    // GET: Logout
    [OutputCache(VaryByParam = "*", Duration = 0, NoStore = true)] // disable caching
    public ActionResult Logout()
    {
        string currentUser = User.Identity.Name;
        int AuthenticationAttempts = 0;

        if (Session["AuthenticationAttempts"] == null || !int.TryParse(Convert.ToString(Session["AuthenticationAttempts"]), out AuthenticationAttempts))
            AuthenticationAttempts = 0;

        AuthenticationAttempts += 1;

        if (AuthenticationAttempts == 1)
        {
            Session["PrevUser"] = User.Identity.Name;
            Session["AuthenticationAttempts"] = AuthenticationAttempts;
            return new HttpUnauthorizedResult();
        }
        else if (string.Compare(Convert.ToString(Session["PrevUser"]), currentUser, true) == 0)  // Somehow it will have echo back, ignore it
        {
            return new HttpUnauthorizedResult();
        }
        else
        {
            Session.Abandon();
            Session.Clear();
            return RedirectToAction("Index", "Home");
        }
    }
}

Error ControllerreturnHttpUnauthorizedResult时,浏览器会提示登录。我可以从 User.Identity.NameErrorController.

中获取新用户名

然而,当它重定向到 HomeController 时,用户被重置为原来的用户,我尝试了以下但还是一样

filterContext.RequestContext.HttpContext.User.Identity.Name
filterContext.HttpContext.User.Identity.Name
filterContext.Principal.Identity.Name

我是否遗漏了什么或者我应该在用户输入后分配主体?

如果有人遇到同样的问题,请确保您已经使用 IIS 进行了测试。

此方法有效,但在 IISExpress 中无效。