繁体   English   中英

跨多个项目的 ASP.NET 用户身份验证

[英]ASP.NET User Authentication across multiple projects

我正在现有系统上构建一个 ASP.NET UI,它由每个项目的单独 SQL 服务器数据库组成。 “企业”数据库列出了所有当前项目,允许匿名用户选择要工作的项目。项目名称存储在会话变量中。 当需要登录时,用户名/密码/角色等将从项目名称指示的数据库中获取。 我已经实现了自己的基本成员资格和角色提供程序来执行此操作,并更改了 web.config 以指定特定页面所需的角色。 (我不使用标准的 ASP.NET 配置工具来管理用户,我有使用我的用户表的现有应用程序)。

这一切最初似乎都有效,但我发现在授权系统检查当前用户所属的角色以确定页面是否可访问时,会话变量尚未加载。 因此,如果我们在 web.config 中有一个 < allow roles="xxx" > 那么授权系统会在加载会话数据之前触发,因此在我知道应该使用哪个项目数据库之前。

[特别是:调用 RoleProvider.GetRolesForUser 时 HttpContext.Current.Session 为 null]

任何解决过这个问题的人都应该确切地知道我在说什么。 因此,我的问题是:

A) 这种情况下的“最佳实践”解决方案是什么?

B)我可以将项目名称存储在授权阶段可用的其他地方(不在会话变量中)吗?

[更新:是的 - 我们可以使用 cookie,假设我们不需要 cookieless 操作]

C)有没有办法在这个较早的时间手动获取会话变量?

我尝试了一个选项来缓存 cookie 中的角色,但在使用该选项进行了几分钟的测试后,我发现 GetRolesForUsers 仍在被调用。

谢谢

更新:
这是对根本问题的另一种描述,它表明“应用程序可以将此信息缓存在 Cache 或 Application 对象中。”:
http://connect.microsoft.com/VisualStudio/feedback/details/104452/session-is-null-in-call-to-getrolesforuser

更新:
这看起来与此处发现的问题相同:
扩展 RoleProvider GetRolesForUser()

更新:
有一个关于在 FormsAuthenticationTicket 中使用 UserData 的建议,但即使没有登录我也需要这些数据。

更新:这些天我通过使用通配符 SSL 证书以更简单的方式解决了这个问题,该证书允许我为每个项目配置子域,因此项目选择直接在 URL 中指定(并且每个项目都有自己的子域)。 在没有子域的本地主机上运行时,我仍然纯粹出于测试目的使用 cookie hack。

原解决方案:

我还没有找到关于这种情况的任何“最佳实践”,但这是我确定的:

1)为了支持匿名用户在项目(即SQL数据库)之间切换,我只是使用一个会话变量来跟踪项目选择。 我有一个全局属性,它使用此项目选择在需要时提供相应的 SQL 连接字符串。

2) 为了支持在应用了角色限制的页面上调用 GetRolesForUser(),我们不能使用会话变量,因为如前所述,当实际调用 GetRolesForUser() 时会话变量尚未初始化(我已经在请求周期的这个早期发现没有办法强制它存在)。

3) 唯一的选择是使用 cookie,或使用 Forms Authentication 票证的 UserData 字段。 我研究了许多关于使用链接到存储在应用程序缓存中的对象的会话/cookie/ID(当会话不可用时可用)的理论,但最终正确的选择是将此数据放在身份验证票中。

4) 如果用户登录到项目,则是通过 ProjectName/UserName 对,因此在我们跟踪用户身份验证的任何地方,我们都需要这两个数据。 在简单的测试中,我们可以将工单中的用户名和项目名称放在单独的 cookie 中,但是它们可能会不同步。 例如,如果我们为项目名称使用会话 cookie 并在登录时勾选“记住我”(为身份验证票创建永久 cookie),那么当会话 cookie 过期(浏览器关闭)时,我们可以得到用户名但没有项目名称)。 因此,我手动将项目名称添加到身份验证票的 UserData 字段中。

5) 我还没有弄清楚如何在不显式设置 cookie 的情况下操作 UserData 字段,这意味着我的解决方案无法在“无cookie”会话模式下工作。

最终的代码变得相对简单。

我在登录页面中覆盖了 LoginView 的 Authenticate 事件:

    //
    // Add project name as UserData to the authentication ticket.
    // This is especially important regarding the "Remembe Me" cookie - when the authentication
    // is remembered we need to know the project and user name, otherwise we end up trying to 
    // use the default project instead of the one the user actually logged on to.
    //
    // http://msdn.microsoft.com/en-us/library/kybcs83h.aspx
    // http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.login.remembermeset(v=vs.100).aspx
    // http://www.hanselman.com/blog/AccessingTheASPNETFormsAuthenticationTimeoutValue.aspx
    // http://www.csharpaspnetarticles.com/2009/02/formsauthentication-ticket-roles-aspnet.html
    // http://www.hanselman.com/blog/HowToGetCookielessFormsAuthenticationToWorkWithSelfissuedFormsAuthenticationTicketsAndCustomUserData.aspx
    // http://stackoverflow.com/questions/262636/cant-set-formsauthenicationticket-userdata-in-cookieless-mode
    //
    protected void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
    {
        string userName = LoginUser.UserName;
        string password = LoginUser.Password;
        bool rememberMe = LoginUser.RememberMeSet;
        if ( [ValidateUser(userName, password)] )
        {
            // Create the Forms Authentication Ticket
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1,
                userName,
                DateTime.Now,
                DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
                rememberMe,
                [ ProjectName ],
                FormsAuthentication.FormsCookiePath);

            // Create the encrypted cookie
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
            if (rememberMe)
                cookie.Expires = DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes);

            // Add the cookie to user browser
            Response.Cookies.Set(cookie);

            // Redirect back to original URL 
            // Note: the parameters to GetRedirectUrl are ignored/irrelevant
            Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, rememberMe));
        }
    }

我有这个全局方法来返回项目名称:

    /// <summary>
    /// SQL Server database name of the currently selected project.
    /// This name is merged into the connection string in EventConnectionString.
    /// </summary>
    public static string ProjectName
    {
        get
        {
            String _ProjectName = null;
            // See if we have it already
            if (HttpContext.Current.Items["ProjectName"] != null)
            {
                _ProjectName = (String)HttpContext.Current.Items["ProjectName"];
            }
            // Only have to do this once in each request
            if (String.IsNullOrEmpty(_ProjectName))
            {
                // Do we have it in the authentication ticket?
                if (HttpContext.Current.User != null)
                {
                    if (HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        if (HttpContext.Current.User.Identity is FormsIdentity)
                        {
                            FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
                            FormsAuthenticationTicket ticket = identity.Ticket;
                            _ProjectName = ticket.UserData;
                        }
                    }
                }
                // Do we have it in the session (user not logged in yet)
                if (String.IsNullOrEmpty(_ProjectName))
                {
                    if (HttpContext.Current.Session != null)
                    {
                        _ProjectName = (string)HttpContext.Current.Session["ProjectName"];
                    }
                }
                // Default to the test project
                if (String.IsNullOrEmpty(_ProjectName))
                {
                    _ProjectName = "Test_Project";
                }
                // Place it in current items so we do not have to figure it out again
                HttpContext.Current.Items["ProjectName"] = _ProjectName;
            }
            return _ProjectName;
        }
        set 
        {
            HttpContext.Current.Items["ProjectName"] = value;
            if (HttpContext.Current.Session != null)
            {
                HttpContext.Current.Session["ProjectName"] = value;
            }
        }
    }

您不能将项目选择回发到某个页面,将该选择添加到会话中,然后重定向到适当的受保护页面,身份验证将在其中启动并强制登录吗?

ASP.NET 会话不会以 cookie 的形式创建,直到您至少在其中放置一项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM