Partager via


Authenticating a User Using a Token

An example of when you might want to use a temporary token for authentication is when you want to improve the performance of your application by passing the token instead of frequently authenticating a user during a single session. You can use the approach described here to retrieve a saved user principal or a user identity from the security cache using a token you previously obtained that represents the user's authenticated identity.

Typical Goals

In this scenario, the goal is to use the token as an alternative to using credentials. You use the token to retrieve the user's principal or identity so that you can present this to other resources when required.

Solution

Call the GetIdentity method of the security cache object, specifying the token that was created when the identity was originally cached.

Using GetIdentity

The following code shows how to use the GetIdentity method. It assumes that you have resolved the ISecurityCacheProvider type through the Enterprise Library container to obtain an instance of the security cache provider you want to use, and stored the reference in a variable named secCache.

Note

For more information on instantiating objects, see Creating and Referencing Enterprise Library Objects.

// Cache the identity (as shown in  the previous scenario). 
IToken token = secCache.SaveIdentity(new GenericIdentity("Username"));

// Retrieve the identity by using the corresponding token.
IIdentity savedIdentity = secCache.GetIdentity(token);
'Usage
' Cache the identity (as shown in  the previous scenario).
Dim token As IToken = secCache.SaveIdentity(New GenericIdentity("Username"))

' Retrieve the identity by using the corresponding token.
Dim savedIdentity As IIdentity = secCache.GetIdentity(token)

For information about resolving Enterprise Library objects in your applications see Creating and Referencing Enterprise Library Objects.

Usage Notes

Alternately, you can use the GetPrincipal or GetProfile method to retrieve a user principal (an object that implements the IPrincipal interface) or a user profile (such as the ASP.NET Profile object).