Useful Extensions for SecurityToken Handling - Convert a SecurityToken to Claims
- by Your DisplayName here!
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);
}