Useful Extensions for SecurityToken Handling - Convert a SecurityToken to Claims

Posted by Your DisplayName here! on Least Privilege See other posts from Least Privilege or by Your DisplayName here!
Published on Fri, 17 Jun 2011 06:50:51 GMT Indexed on 2011/06/20 16:38 UTC
Read the original article Hit count: 310

Filed under:

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

© Least Privilege or respective owner

Related posts about IdentityModel