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

时间:2012-01-23 09:23:58

标签: c# asp.net authorization

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

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

[具体来说:当调用RoleProvider.GetRolesForUser时,HttpContext.Current.Session为null]

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

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

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

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

C)有没有办法在此时手动获取会话变量?

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

由于

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

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

更新:
有人建议在FormsAuthenticationTicket中使用UserData,但即使没有登录也需要这些数据。

2 个答案:

答案 0 :(得分:2)

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

原始解决方案:

我没有找到任何“最佳实践”来写这个场景,但这是我已经解决的问题:

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

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

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

4)如果用户登录到项目,则通过ProjectName / UserName对,因此在我们跟踪用户身份验证的任何地方,我们都需要这两个数据。在简单的测试中,我们可以使用票证中的用户名和单独的cookie中的项目名称,但这些可能会失去同步。例如,如果我们使用会话cookie作为projectname并在我们登录时勾选“记住我”(为身份验证票证创建一个永久性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;
            }
        }
    }

答案 1 :(得分:1)

你不能将项目选择回发到某个页面,将该选择添加到会话,然后重定向到适当的受保护页面,auth将启动并强行登录吗?

在您放置至少一个项目之前,不会以cookie的形式创建ASP.NET会话。

相关问题