Re: Forms Authentication & Application Events

From: Kim Bach Petersen (msnews@kensho.dk)
Date: 02/18/03


From: "Kim Bach Petersen" <msnews@kensho.dk>
Date: Tue, 18 Feb 2003 11:20:21 +0100


> Is there an event that fires in the global.asax when a user is
> authenticated?

Yes: Application_AuthenticateRequest.

> And how do I determine if they already have the
> authentication ticket?

The ticket is a cookie, you simply check if its there.

Example below gets user roles from a cookie or a database.

Kim :o)

 Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As
EventArgs)
  If Request.IsAuthenticated Then
   If (Context.User.Identity.AuthenticationType = "Forms") Then
    Dim arrRoller As String()
    If Request.Cookies("MyTicket") Is Nothing Then
     Dim MyDatabase As New MySQLodbc()
     Dim strRoller As String = MyDatabase.GetUserRoles(User.Identity.Name)
     Dim Ticket As New FormsAuthenticationTicket(1,
Context.User.Identity.Name, DateTime.Now, DateTime.Now.AddHours(1), False,
strRoller)
      Dim strCookie As String = FormsAuthentication.Encrypt(Ticket)
     Response.Cookies("MyTicket").Value = strCookie
     Response.Cookies("MyTicket").Path = "/"
     Response.Cookies("MyTicket").Expires = DateTime.Now.AddMinutes(30)
     arrRoller = Split(strRoller,",")
    Else
     Dim Ticket As FormsAuthenticationTicket =
FormsAuthentication.Decrypt(Context.Request.Cookies("MyTicket").Value)
     arrRoller = Ticket.Userdata.Split(New Char() {","c})
    End If
    Context.User = New GenericPrincipal(Context.User.Identity, arrRoller)
   End If
  End If
 End Sub

>
> Here's my problem: I have some session state that I need to initialize
> upon login; using forms authentication and a dB. I also give them the
> option of keeping the authentication cookie alive between sessions.
> So, I would like to catch the authentication event, determine the
> state of my session, and if need be re-query for the session data from
> my dB.
>
> Ex.
>
> Normal Login - use username and password to retrieve CustID and other
> data from dB; save to session
>
> Existing Auth. Ticket - retrieve CustID from cookie, query dB for
> other data and save to session
>
> Thanks