1

我一直在花一些时间试图掌握在我的应用程序中处理身份验证/授权的最佳方法。我正在使用 Windows 身份验证,并且能够读取用户名。

为了授权用户,我想查询数据库以获取他们的角色并为具有该角色的用户创建自定义主体。

我相信我下面的内容会起作用,但是,我只是好奇是否有更好的方法来查询数据库一次而不是使用会话变量作为检查?

下面的代码在我的 Global.asax 中。

protected void Application_AuthenticateRequest(object sender, EventArgs args)
    {
        if (HttpContext.Current != null)
        {
            if (this.Session["Authenticated"] == null)
            {
                using (AppToolsEntities db = new AppToolsEntities())
                {
                    var user = db.ADObjects.Where(x => x.CN == User.Identity.Name.RemoveDomain()).FirstOrDefault();
                    string[] roles = new string[] { user.Title == "EA" ? "Reviewer" : "Admin" };
                    GenericPrincipal principal = new GenericPrincipal(HttpContext.Current.User.Identity, roles);
                    Thread.CurrentPrincipal = HttpContext.Current.User = principal;
                    this.Session["Authenticated"] = true;
                }
            }
        }
    }

我会以正确的方式解决这个问题吗?

提前致谢。

4

0 回答 0