【问题标题】:Why base.AuthorizeCore(httpContext); is true before any authentication or authorisation?为什么 base.AuthorizeCore(httpContext);在任何认证或授权之前是真的吗?
【发布时间】:2016-02-04 06:05:14
【问题描述】:

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

 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 应该是假的。

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

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

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

【问题讨论】:

  • 你试过用HttpContext.User.Identity.IsAuthenticated代替base.AuthorizeCore吗?

标签: asp.net-mvc c#-4.0 authorization


【解决方案1】:

这是在 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。

尝试在隐身浏览器窗口中访问受保护的资源。如果这不起作用,请检查您的 LogOff 控制器,它应该类似于以下内容:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 2021-08-28
    • 1970-01-01
    相关资源
    最近更新 更多