Autologue Implementation for ASP.NET MVC
I am trying to get ASP.NET MVC membership. There are several pages that require authentication. Others that may have guests and authorized members. Very similar to StackOverflow. They can do it anonymously or as a registered user.
We also have a custom database schema for handling items (not the default for ASP.NET). So I would like to write my own membership / principal code. So far it works well BUT I am having problems with session expiration and being able to implement the "Remember me" functionality.
I'm using FormsAuthentication.SetAuthCookie (username, rememberMe) to set cookie forms, but I'll say the user leaves the machine for 20 minutes, or IIS recycles my session and I get very inconsistent user state.
Where can I catch the 'Remember me' cookie and how can I login again? Essentially I am storing the username and password and then looking at the cookie in Application_BeginRequest or something?
source to share
If I read it correctly, it looks like you would expect ASP.NET to detect the persistent cookie and re-establish that state of the last user session. It doesn't work: the authentication cookie and the asp.net session are two independent things, so you will have instances when the user comes back to the site and authenticates through the persistent AuthCookie, but has a completely new (empty) session data.
Assuming AuthCookie is configured correctly, you might find that the user is authenticated with User.Identity.IsAuthenticated
, which is not affected by IIS navigation or session logging. The username is displayed in User.Identity.Name
.
If you need to re-initialize some session data when the user returns to the site, you will have to do it manually. If this is really what you are asking, it is difficult to answer without knowing more about your application, but consider the event Session_Start
and Session_End
in the global.asax. Alternatively, you can just check the session object and repopulate each time it is empty (after the session expires), like this:
//get some user info from session or db if session is null
string preferredName;
if (User.Identity.IsAuthenticated)
{
object o = Session["preferredName"];
if (o == null)
{
preferredName = repository.GetUser(User.Identity.Name).PreferredName;
Session["preferredName"] = preferredName; //save to session so this isn't necessary next time
}
else
{
preferredName = (string)o;
}
}
else
{
preferredName = "anon";
}
source to share