Search code examples
c#adfsfederation

How to read thumbprints of signing certificates from Federation Metadata XML?


I want to be able to monitor the signing certificates of trusted parties ADFS. One approach is to read the Federation Metadata XML manually and parse the KeyInfo - elements and create the X509Certificate from the base64-encoded data: see this good article

After some reading i found that MetadataSerializer I can easily create EntityDescriptor for further investigations from the XML. As an example, one can get the Metadata for Windows Live login:

string uri = "https://login.microsoftonline.com/38cda3b4-71fa-4748-a48e-e50ef1ebfe00/federationmetadata/2007-06/federationmetadata.xml";
using (var reader = XmlReader.Create(uri))
{
    var serializer = new MetadataSerializer();
    serializer.CertificateValidationMode = X509CertificateValidationMode.None;
    EntityDescriptor metadata = (EntityDescriptor)serializer.ReadMetadata(reader);
}

The descriptor exposes a property RoleDescriptors which simply wraps up all the descriptors inside the metadata, including the security keys for encrypting or signing. But I am not able to access the certificate data in order to read out the thumbprints. See the simplified code below:

// metadata from above
SecurityKeyIdentifierClause keyIdentifier = metadata.RoleDescriptors.First().Keys.First().KeyInfo[0];
// keyIdentifier.certificate ... => private, exposes XCertificate2

Any ideas to get the thumbprint with that approach rather than the manual XML parsing?

Cheers!


Solution

  • It all comes down to using the X509RawDataKeyIdentifierClause rather than the abstract base of it:

     X509RawDataKeyIdentifierClause keyIdentifier = metadata.RoleDescriptors.First().Keys.First().KeyInfo[0] as X509RawDataKeyIdentifierClause;
    
     if ( keyIdentifier != null )
     {
          X509Certificate2 cert = new X509Certificate2(keyIdentifier.GetX509RawData());
          string thumbprint     = cert.Thumbprint;
     }