How To: decrypt a GenericXmlSecurityToken with Geneva Beta 2

This post had a lot of visits so I have updated it to work with Geneva Beta 2

   1: public static ClaimsIdentityCollection ToClaimsIdentityCollection(this GenericXmlSecurityToken originalToken, TrustVersion trustVersion, X509Certificate2 signature, X509Certificate2 encryption)
   2: {
   3:     var tokenReader = new StringReader(originalToken.TokenXml.OuterXml);
   4:     var reader = XmlReader.Create(tokenReader);
   5:  
   6:     var privateKeyToken = new X509SecurityToken(encryption);
   7:     var issuerKeyToken = new X509SecurityToken(signature);
   8:     var tokens = new List<SecurityToken>();
   9:     tokens.Add(privateKeyToken);
  10:     tokens.Add(issuerKeyToken);
  11:     SecurityTokenResolver outOfBandTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new ReadOnlyCollection<SecurityToken>(tokens), false);
  12:  
  13:     var handlers = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
  14:     var samlHandler = handlers[typeof(SamlSecurityToken)] as Saml11SecurityTokenHandler;
  15:     samlHandler.ContainingCollection[typeof(EncryptedSecurityToken)].Configuration.ServiceTokenResolver = outOfBandTokenResolver;
  16:     var issuerRegistry = new ConfigurationBasedIssuerNameRegistry();
  17:     issuerRegistry.AddTrustedIssuer(signature.Thumbprint, signature.Subject);
  18:     samlHandler.Configuration.IssuerNameRegistry = issuerRegistry;
  19:  
  20:     var serializer = new SecurityTokenSerializerAdapter(handlers,
  21:         SecurityVersion.WSSecurity11,
  22:         trustVersion,
  23:         trustVersion == TrustVersion.WSTrust13 ? SecureConversationVersion.WSSecureConversation13 : SecureConversationVersion.WSSecureConversationFeb2005,
  24:         false,
  25:         null,
  26:         null,
  27:         null);
  28:  
  29:     var samlSecurityToken = serializer.ReadToken(reader, outOfBandTokenResolver);
  30:     reader.Close();
  31:  
  32:     var claims = handlers.ValidateToken(samlSecurityToken);
  33:  
  34:     return claims;
  35: }
 

Published: May 20 2009

blog comments powered by Disqus