views:

17

answers:

2

I have an ASP.NET WebForms page with forms authentication. When users create a login, I use 'remember me' to create the authentication cookie.

What I now want to do is check the time of their last access. But LastLogin time is updated only when the user uses the login control (which they don't need to use when they have the authentication cookie on their machine), and LastActivity control is updated before any of my code runs.

It looks like the only way I can do this is to hook into the application event Application_AuthenticateRequest - right? Or is there some better way to do this?

Thanks!

A: 

Hi,

Yes you will want to hook the FormsAuthenticationModule.Authenticate event. You can do this by adding a module to your web application. See the following sample module code.

 public class BasicAuthenticateModule : IHttpModule
  {
    public BasicAuthenticateModule()
    {
    }

    public void Dispose()
    {
    }

    public void Init(HttpApplication context)
    {
      foreach (string name in context.Modules.Keys)
      {
        if (name == ApplicaionModules.FormsAuthentication)
        {
          FormsAuthenticationModule module = (FormsAuthenticationModule)context.Modules[name];
          module.Authenticate += new FormsAuthenticationEventHandler(module_Authenticate);
          break;
        }
      }
    }

    private void module_Authenticate(object sender, FormsAuthenticationEventArgs e)
    {

    }
  }

Enjoy!

Doug
Unfortunately handleAuthenticate is no good because that's called for every single page view. I want to know when the user's not been to the site for a while then comes back - i.e. their session has expired. So I guess the only way is by using the Session_End event.
Ian Grainger
A: 

Instead I used the session_start event in Global.asax.

In there I've stored the current and previous session start DateTime's against the user in the DB (moving the current to the previous each time). This gets me the time of a user's previous session.

It might be better to use session_end - but that's not the time the user left the page, it's [timeout] time after their last activity - so this is a fairly good solution.

Ian Grainger