Search code examples
eventsglobal-asaxwifwindows-identity

How do I handle the event SessionSecurityTokenReceived in Global.asax?


I'm trying to set up sliding sessions in WIF and need to handle SessionSecurityTokenReceived.

I'm sure I'm doing something dumb here... but VS2010 keeps on telling me that There is no applicable variable or member in the spot illustrated below. Can anyone point me in the right direction? I've searched high and low for actual samples of how to define the handling of this event, but I can't find a single one.

Global.asax

protected void Application_Start()
{

    FederatedAuthentication.WSFederationAuthenticationModule.SecurityTokenReceived 
           += SessionAuthenticationModule_SessionSecurityTokenReceived;
     //         ^^^ There is no applicable variable or member
}



void SessionAuthenticationModule_SessionSecurityTokenReceived(object sender, SessionSecurityTokenReceivedEventArgs e)
{
            DateTime now = DateTime.UtcNow;
            DateTime validFrom = e.SessionToken.ValidFrom;
            DateTime validTo = e.SessionToken.ValidTo;
            if ((now < validTo) &&
            (now > validFrom.AddMinutes((validTo.Minute - validFrom.Minute) / 2))
            )
            {
                SessionAuthenticationModule sam = sender as SessionAuthenticationModule;
                e.SessionToken =  sam.CreateSessionSecurityToken(
                    e.SessionToken.ClaimsPrincipal, 
                    e.SessionToken.Context,
                    now,
                    now.AddMinutes(2), 
                    e.SessionToken.IsPersistent);
                e.ReissueCookie = true;
            }
            else
            {
                //todo: WSFederationHelper.Instance.PassiveSignOutWhenExpired(e.SessionToken, this.Request.Url);

                // this code from: http://stackoverflow.com/questions/5821351/how-to-set-sliding-expiration-in-my-mvc-app-that-uses-sts-wif-for-authenticati

                var sessionAuthenticationModule = (SessionAuthenticationModule)sender;

                sessionAuthenticationModule.DeleteSessionTokenCookie();

                e.Cancel = true;
            }
  } 

Solution

  • I don't think you need the event subscription. Remove the subcription on start and just use

    SessionAuthenticationModule_SessionSecurityTokenReceived

    ASP.Net will wire that for you. (The module has to be named "SessionAuthenticationModule" and it is by default).

    If you are working on sliding sessions, this blog post by Vittorio is pretty good: http://blogs.msdn.com/b/vbertocci/archive/2010/06/16/warning-sliding-sessions-are-closer-than-they-appear.aspx