Authentication and Session

Michael Schwarz on Monday, July 30, 2007

In my current project I'm using a own User object that I store in the HttpContext.Session to have personalized data available without connecting on each AJAX method / page refresh to the database. If the session will end because of timeouts, Web server resets/crash or application pool recycle this data will not be available any more, I have to read all again and store it in the session.

I built a very simple GetCurrentUser method that will return this data in an AJAX method or in the page. This isn't something special, but it is very easy to use if you need something similar.

public sealed class UserFactory
{
public static MyUser GetCurrentUser()
{
// If the HttpContext is missing we cannot access 
// the session or get any identity from logged-in users.

if(HttpContext.Current == null)
throw new NullReferenceException("The HttpContext is missing.");

if(HttpContext.Current.Session != null && 
HttpContext.Current.Session["user"] != null)
{
// Check if there is a MyUser object still available in session.

try
{
MyUser user = HttpContext.Current.Session["user"] as MyUser;

if(user != null)
return user;
}
catch(Exception)
{
}
}

if(HttpContext.Current.User.Identity.IsAuthenticated && 
!String.IsNullOrEmpty(HttpContext.Current.User.Identity.Name))
{
// Create a new MyUser instance from the authenticated
// user name.

MyUser user = new MyUser(HttpContext.Current.User.Identity.Name);

// Add the new MyUser instance to the session for
// further requests.

if(HttpContext.Current.Session != null)
HttpContext.Current.Session["user"] = user;

return user;
}
else
{
// If not authenticated we trow an SecurityException which
// can be identified in the AJAX response (res.error.Type).
// If this happens we redirect to the login page or ask
// for user credentials to get authenticated with the built-in
// AjaxPro authentication service.

throw new System.Security.SecurityException("Not authenticated.");
}
}
}   

The following demo AjaxMethod will always return the user specific data if the user is correct authenticated and/or the user has the same session as on last request. Any exception that is thrown in the GetCurrentUser method will be send to the client-side JavaScript where you then can decide what to do (i.e. ask for user credentials again).

public class AjaxMethods
{
[AjaxPro.AjaxMethod]
public static DataTable GetMyFavorites()
{
MyUser user = UserFactory.GetCurrentUser();

// Now I can access the user properties. If the above method
// fails (throw any exception) it will be handled by AjaxPro
// and returned the exception details to client-side JavaScript.

return user.GetMyFavorites();
}
}