更新:这些天我通过使用通配符 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;
}
}
}