Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreasbotsikas/11356884 to your computer and use it in GitHub Desktop.
Save andreasbotsikas/11356884 to your computer and use it in GitHub Desktop.
A Saml2SecurityTokenHandler that replaces the ServiceTokenResolver to enable token decryption
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
using Saml2SecurityTokenHandler = Microsoft.IdentityModel.Extensions.Saml2SecurityTokenHandler;
namespace Owin.Security.WsFederation
{
/// <summary>
/// Saml2SecurityToken handler that can decrypt the encrypted saml2
/// </summary>
class EncryptedSaml2SecurityTokenHandler : Saml2SecurityTokenHandler
{
private SecurityTokenResolver EncryptServiceTokenResolver { get; set; }
/// <summary>
/// Decrypt the saml token using the given certificate
/// </summary>
/// <param name="encryptingCertificate">The relying party's certificate to use in order to decrypt the token</param>
public EncryptedSaml2SecurityTokenHandler(X509Certificate2 encryptingCertificate)
{
// Set the encrypting certificate in order to be able to decrypt the token
List<SecurityToken> tokens = new List<SecurityToken>() { new X509SecurityToken(encryptingCertificate) };
this.EncryptServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), false);
}
/// <summary>
/// Override to replace the empty SrviceTokenResolver with the X509 one
/// </summary>
public override bool CanReadToken(string tokenString)
{
this.Configuration.ServiceTokenResolver = EncryptServiceTokenResolver;
return base.CanReadToken(tokenString);
}
/// <summary>
/// Override to replace the empty SrviceTokenResolver with the X509 one
/// </summary>
public override SecurityToken ReadToken(XmlReader reader)
{
this.Configuration.ServiceTokenResolver = EncryptServiceTokenResolver;
return base.ReadToken(reader);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment