为什么 base.AuthorizeCore(httpContext);在任何身份验证或授权之前是真的吗?

Why base.AuthorizeCore(httpContext); is true before any authentication or authorisation?

在我的自定义授权属性中:

 public class AuthorizeUserAttribute : AuthorizeAttribute
{

    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {
            return false;
        }

        string privilegeLevels = string.Join("", httpContext.Session["UserRole"]);
        privilegeLevels = privilegeLevels.Trim();
        AccessLevel = AccessLevel.Trim();
        string[] usersWithAcces = AccessLevel.Split(',');
        foreach (string u in usersWithAcces)
        {
            if (privilegeLevels.Equals(u))
            {
                return true;
            }
        }
        return false;
    }
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new RedirectToRouteResult(
                     new RouteValueDictionary(
                         new
                         {
                             controller = "UserAccount",
                             action = "LogIn"
                         })
                     );
    }
}

}

var isAuthorized 始终为真。按照我的逻辑,它应该是这样的:

  1. 第一次尝试访问受保护的方法 isAuthorized 应该是 false。

  2. 用户被重定向到登录页面。

  3. 如果识别出用户的详细信息,则 isAuthorized 为 true 并执行下一条语句。

可能我遗漏了什么,但如果有人能告诉我为什么它总是正确的,我将不胜感激。

这就是 AuthorizeCore(HttpContext) 中发生的事情:

protected virtual bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
        {
            throw new ArgumentNullException("httpContext");
        }

        IPrincipal user = httpContext.User;
        if (!user.Identity.IsAuthenticated)
        {
            return false;
        }

        if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))
        {
            return false;
        }

        if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole))
        {
            return false;
        }

        return true;
    }

如您所见,这意味着当前用户已经登录(浏览器中有一个 cookie)。假设您使用 FormAuthentication 我最好的客人是您没有正确处理 cookie。

尝试在隐身浏览器中访问受保护的资源window。如果这不起作用,请检查您的注销控制器,它应该看起来像这样:

public ActionResult LogOff()
{
   FormsAuthentication.SignOut();

   return RedirectToAction("Login", "Account");
}