【问题标题】:base.AuthorizeCore(httpContext) is allways false - how to find the reasonbase.AuthorizeCore(httpContext) 总是假的 - 如何找到原因
【发布时间】:2016-02-02 06:19:02
【问题描述】:

您好,我正在尝试使用自定义授权属性,但 base.AuthorizeCore 总是返回 false。我不知道我在哪里做错了。你能告诉我问题出在哪里吗?我的 AuthorizeAttribute:

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {
            return false;
        }
        string roles = string.Join("", httpContext.Session["UserRole"]);
       // string roles = string.Join("", HttpContext.Current.Session["UserRole"]);
        if (Roles.Contains(roles))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

我的登录方法:

 public ActionResult LogIn()
 {
        var model = new UserModel();
        return View(model);
 }


 [HttpPost]
 public ActionResult LogIn(UserModel model)
 {

        if (!ModelState.IsValid)
        {
            return View("LogIn", model);
        }
        else
            {
            var usermodelDB = _UserAccountService.GetUser(model.Password);
            if (model.userName == usermodelDB.userName && model.Password==usermodelDB.Password)
            {


                model.userRole = usermodelDB.userRole;
                FormsAuthentication.SetAuthCookie(model.userRole, true);
                System.Web.HttpContext.Current.Session["UserRole"] = usermodelDB.userRole;
                var ia =System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
            }
            return View("LogIn", model);
        }
 }

以及访问受限的方法:

[AuthorizeUser(Roles="User")]
public ActionResult Index(int page=0)
{
    return View();
}

【问题讨论】:

    标签: c# asp.net-mvc authorization


    【解决方案1】:

    很可能该用户不在该角色中。 AuthorizeCore 查看用户的身份并测试用户所处的角色。因此如果用户被授权,则返回true。 (+)

    【讨论】:

    • 谢谢,从 Db 获取的角色是“用户”,属性中的角色是“用户”
    【解决方案2】:

    对我来说,我删除了网站的 cookie,然后它就起作用了。似乎两个应用程序使用相同的数据库表来存储用户。更改 cookie 名称有助于解决错误:https://stackoverflow.com/a/25039278/7429464

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多