I am currently developing a site using ASP.NET MVC 3, I am using Nhibernate. I created a custom MembershipProvider as described below.
My question is time to record the user authentication in a session in ValidateUser method and retrieves it in GetUser.
From what I noticed you can not use Session in the ValidateUser, but it is not correct to use Cache, since the storage is not per user session.
How do I do?
class MyMembershipProvider : MembershipProvider
{
public override MembershipUser GetUser(string username, bool userIsOnline)
{
var membershipUser = MyMembershipUser)HttpContext.Current.Cache.Get(username);
// Is not possible
// var membershipUser = (MyMembershipUser) HttpContext.Current.Session[username];
return membershipUser;
}
public override bool ValidateUser(string username, string password)
{
var usuario = UsuarioRepository.GetUsuarioAuthentication(username, password);
if (usuario != null)
{
HttpContext.Current.Cache.Add(username, new MyMembershipUser(usuario.Id, usuario.Email), null,
Cache.NoAbsoluteExpiration, FormsAuthentication.Timeout,
CacheItemPriority.Default, null);
// Is not possible
// HttpContext.Current.Session.Add(username, new MyMembershipUser(usuario.Id, usuario.Email));
return true;
}
return false;
}
}
Session is not involved at all when you use ASP.NET Membership with Forms Authentication.
Once the user has successfully authenticated, simply call
and an authenication cookie is automatically created for you. Don’t call this in ValidateUser(), but rather from the client code that calls ValidateUser().
The authentication cookie is completely independent of the session cookie.
Refer Forms Authentication on MSDN for more info.
If you want to cache your authenticated user’s user details, again this should be done in the client code that calls Membership.ValidateUser(), not in the membership provider itself. The membership provider GetUser() and ValidateUser() should do as their names suggest, and not have any other side effects.