如何在Global.asax中处理事件SessionSecurityTokenReceived?

时间:2011-11-14 16:55:56

标签: events global-asax wif windows-identity

我正在尝试在WIF中设置滑动会话,需要处理SessionSecurityTokenReceived

我确定我在这里做了一些愚蠢的事......但VS2010继续告诉我There is no applicable variable or member在下图所示的位置。谁能指出我正确的方向?我已经搜索了如何定义这个事件的处理的实际样本的高低,但我找不到一个。

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;
            }
  } 

2 个答案:

答案 0 :(得分:9)

我认为您不需要订阅活动。删除开始时的描述,然后使用

SessionAuthenticationModule_SessionSecurityTokenReceived

ASP.Net将为您提供连线。 (该模块必须命名为“SessionAuthenticationModule”,默认情况下)。

如果您正在进行滑动会话,那么Vittorio的这篇博文非常好:http://blogs.msdn.com/b/vbertocci/archive/2010/06/16/warning-sliding-sessions-are-closer-than-they-appear.aspx

答案 1 :(得分:0)

不是在Global.asax中定义它,而是创建一个继承SessionAuthenticationModule的新类:

public class CustomAuthenticationModule : SessionAuthenticationModule
{
   public CustomAuthenticationModule()
   {
      this.SessionSecurityTokenReceived += new EventHandler<SessionSecurityTokenReceivedEventArgs>(CustomAuthenticationModule_SessionSecurityTokenReceived); 
   }

   void CustomAuthenticationModule_SessionSecurityTokenReceived(object sender, SessionSecurityTokenReceivedEventArgs e)
   {
      // Your code
   }
}

然后在您的web.config中,将默认的SessionAuthentication模块替换为您的新模块:

<modules>
   <add name="SessionAuthenticationModule" type="CustomAuthenticationModule" preCondition="managedHandler"/>
</modules>