Reputation: 31847
I'm testing a WebRole with multiples instances in Windows Azure to test the load balancer. The code that I have to authenticate users is the following:
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;
}
Here are my questions. I tested the WebRole with two instances in Azure:
Current.Request.Cookies
and the HttpContext.Current.Session["__SessionSID"]
were ok.Someone could explain it? I the session shared among all the WebRole instances?
Upvotes: 1
Views: 2043
Reputation: 49095
It all falls down to the Session State Provider
configuration.
Typically you would have to implement custom provider (that would usually be Windows Azure Cache or SQL Azure) to allow persisted session data across multiple instances.
http://msdn.microsoft.com/en-us/library/windowsazure/gg185668.aspx
Once logged in (no matter on which instance) you're receiving a cookie with a SessionID in it.
Further requests to any instance will cause the application to request your session data from the configured provider.
Upvotes: 2