MVC 4 Windows身份验证&自定义授权

时间:2013-07-11 16:38:37

标签: asp.net-mvc-4 authorization

我花了一些时间试图掌握在我的应用中处理身份验证/授权的最佳方法。我正在使用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;
                }
            }
        }
    }

我是以正确的方式来做这件事的吗?

提前致谢。

0 个答案:

没有答案