English

How To: Handle authentication tokens with .NET

Summary

Authentication tokens can be stored and re-used until they expire, as specified by their timeout value. This article details one way to handle tokens in a .NET environment.

Procedure

This code sample requests an hour-long token every 59 minutes ensuring there is always a valid token. The request is handled on a separate thread than the rest of the application so it will not interfere. This token will be shared by all users of all applications in this solution.

  1. Within the solution's Global.asax.vb, include the following code:

    Code:
    Public Sub refreshToken(ByVal k As String, ByVal v As Object, ByVal r As System.Web.Caching.CacheItemRemovedReason)
    Dim onRemove As System.Web.Caching.CacheItemRemovedCallback = New System.Web.Caching.CacheItemRemovedCallback(AddressOf Me.refreshToken)
    Dim authWS As New Auth.Authentication
    Dim token As String = authWS.getToken("username", "password")
    HttpRuntime.Cache.Insert("AUTHENTICATION_TOKEN", token, Nothing, DateTime.Now.AddMinutes(59), System.Web.Caching.Cache.NoSlidingExpiration, Caching.CacheItemPriority.High, onRemove)
    End Sub

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    refreshToken(Nothing, Nothing, Nothing)
    End Sub

  2. Call this variable when a token is needed as an input to a method by using the following code:

    Code:
    Cache.Get("AUTHENTICATION_TOKEN")