Useful Extensions for SecurityToken Handling – Convert a SecurityToken to Claims

That’s a very common one:

public static IClaimsPrincipal ToClaimsPrincipal(
this SecurityToken token, X509Certificate2
signingCertificate)
{
   
var
configuration = CreateStandardConfiguration(signingCertificate);
   
return token.ToClaimsPrincipal(configuration.CreateDefaultHandlerCollection());
}
 
public static IClaimsPrincipal ToClaimsPrincipal(this SecurityToken token, 
X509Certificate2 signingCertificate, string
audienceUri)
{
   
var
configuration = CreateStandardConfiguration(signingCertificate);

    configuration.AudienceRestriction.AudienceMode =
AudienceUriMode
.Always;
    configuration.AudienceRestriction.AllowedAudienceUris.Add(
new Uri
(audienceUri));

   
return token.ToClaimsPrincipal(configuration.CreateDefaultHandlerCollection());
}
 
public static IClaimsPrincipal ToClaimsPrincipal(
this SecurityToken token, SecurityTokenHandlerCollection
handler)
{
   
var
ids = handler.ValidateToken(token);
   
return ClaimsPrincipal.CreateFromIdentities(ids);
}
 
private static SecurityTokenHandlerConfiguration CreateStandardConfiguration(
X509Certificate2
signingCertificate)

{
   
var configuration = new SecurityTokenHandlerConfiguration
();

    configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;
    configuration.IssuerNameRegistry = signingCertificate.CreateIssuerNameRegistry();
    configuration.IssuerTokenResolver = signingCertificate.CreateSecurityTokenResolver();
    configuration.SaveBootstrapTokens =
true
;

    return configuration;
}

 
private static IssuerNameRegistry CreateIssuerNameRegistry(this X509Certificate2 certificate)
{
   
var registry = new ConfigurationBasedIssuerNameRegistry
();
    registry.AddTrustedIssuer(certificate.Thumbprint, certificate.Subject);

   
return registry;
}
 
private static SecurityTokenResolver CreateSecurityTokenResolver(
this X509Certificate2
certificate)
{
   
var tokens = new List<SecurityToken
>
    {
       
new X509SecurityToken
(certificate)
    };

   
return SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), true);
}
 
private static SecurityTokenHandlerCollection CreateDefaultHandlerCollection(
this SecurityTokenHandlerConfiguration
configuration)
{
   
return 
SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(configuration);
}
 
This entry was posted in IdentityModel. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s