1

我正在Windows Azure 中测试具有多个实例的WebRole以测试负载平衡器。我必须对用户进行身份验证的代码如下:

    protected void Application_AcquireRequestState(Object sender, EventArgs e)
    {
        HttpCookie authCookie = 
            HttpContext.Current.Request.Cookies
               [FormsAuthentication.FormsCookieName];

        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = 
                FormsAuthentication.Decrypt(authCookie.Value);

            SetUserCredentials(authTicket.Name, authTicket.UserData);
        }
    }

    private void SetUserCredentials(string userName, string securityConfig)
    {
        Credentials auth = GetSessionCredentials();

        if (auth == null && HttpContext.Current.Session != null)
        {
            log.DebugFormat("Credentials not available in session variable. Building credentials to __SessionSID.");

            SID sid = 
               AuthenticationHelper.Get().
                  GetAuthenticatedSIDFromName(userName, securityConfig);

            if (sid == null)
            {
                FormsAuthentication.SignOut();
                FormsAuthentication.RedirectToLoginPage();
                return;
            }

            auth = new Credentials(sid);

            if (HttpContext.Current.Session != null)
            {
                log.DebugFormat("Saving credentials in a session variable");
                HttpContext.Current.Session.Add("__SessionSID", auth);
            }
        }

        log.DebugFormat("Time setting user credentials for user: {0} {1}ms", userName, Environment.TickCount - ini);
    }

    private Credentials GetSessionCredentials()
    {
        if (HttpContext.Current == null)
            return null;
        if (HttpContext.Current.Session == null)
            return null;

        return HttpContext.Current.Session["__SessionSID"] as Credentials;
    }

这是我的问题。我在 Azure 中使用两个实例测试了 WebRole:

  • 假设我登录并且 WebRole 实例 A 执行身份验证。
  • 当我发出新请求,并且请求转到 WebRole 实例 B 时,其中的 authTicketCurrent.Request.CookiesHttpContext.Current.Session["__SessionSID"]都正常。

有人可以解释一下吗?我在所有 WebRole 实例之间共享会话?

4

1 回答 1

2

这一切都归结为Session State Provider配置。

通常,您必须实现自定义提供程序(通常是 Windows Azure 缓存或 SQL Azure)以允许跨多个实例的持久会话数据。

http://msdn.microsoft.com/en-us/library/windowsazure/gg185668.aspx

登录后(无论在哪个实例上),您都会收到一个带有 SessionID 的 cookie。

对任何实例的进一步请求将导致应用程序从配置的提供程序请求您的会话数据。

于 2013-03-07T12:44:14.477 回答