Reputation: 5408
I'm not sure if this is the best way to do it, but I want to keep a user object alive during all requests of the current user. From reading several resources I learned that you should create your own IPrinciple which holds this. But I don't want to trigger the database every authentication request. Any recommendations on how to handle this? Is caching the db request a good idea?
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
User user;
using (HgDataContext hg = new HgDataContext())
{
if (Session["user"] != null)
{
user = (from u in hg.Users where u.EmailAddress == authTicket.Name select u).Single();
} else
{
user = Session["user"] as User;
}
}
var principal = new HgPrincipal(user);
Context.User = principal;
}
}
Upvotes: 7
Views: 5981
Reputation: 5131
Creating your own IPrincipal implementation is the best way to do it. It's not a problem to cache the data for a user as long as you refresh it if it is updated. Usually only the user himself has the ability to change his personal data so it is not hard to do it. You can see an easy way to change the current user in this blog post.
Upvotes: 0
Reputation: 5408
I'm now using the following code which caches the user, take care that you remove the cache after an update!
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
User user;
Cache cache = HttpContext.Current.Cache;
using (HgDataContext hg = new HgDataContext())
{
user = cache[authTicket.Name] as User;
if (user == null)
{
user = (from u in hg.Users where u.EmailAddress == authTicket.Name select u).Single();
cache[authTicket.Name] = user;
}
}
var principal = new HgPrincipal(user);
Context.User = principal;
}
}
Upvotes: 2
Reputation: 36319
Session is probably the appropriate way to do this, and in fact is one of the few uses of Session that I'd advocate.
Upvotes: 3