Search code examples
sslwif

When trying to deserialize SAML tokens, can I read an SSL Cert from file instead of Certificate store


I would like to something like this:

<microsoft.identityModel>
    <service>
      <serviceCertificate>
        <certificateReference filename="App_Data/my.domain.com.crt" />
      </serviceCertificate>
    </service>
</microsoft.identityModel>

Solution

  • I figured it out. Comment out this part in web.config

      <!--<serviceCertificate>
        <certificateReference x509FindType="FindByThumbprint" findValue="" storeLocation="LocalMachine" storeName="My" />
      </serviceCertificate>-->
    

    Add this code to global.asax

        protected void Application_Start()
        {
            Microsoft.IdentityModel.Web.FederatedAuthentication.ServiceConfigurationCreated += new EventHandler
                <Microsoft.IdentityModel.Web.Configuration.ServiceConfigurationCreatedEventArgs>(AttachCert);
        }
    
        protected void AttachCert(object sender, Microsoft.IdentityModel.Web.Configuration.ServiceConfigurationCreatedEventArgs e)
        {
            var filename = string.Format("{0}\\{1}\\{2}", System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "App_Data\\certificates", "CERTNAME.pfx");
            var cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(filename, "YOURPASSWORD");
    
            var _configuration = e.ServiceConfiguration;
            _configuration.ServiceCertificate = cert;
    
            var certificates = new List<System.IdentityModel.Tokens.SecurityToken> { new System.IdentityModel.Tokens.X509SecurityToken(
                    _configuration.ServiceCertificate) };
    
            var encryptedSecurityTokenHandler =
                    (from handler in _configuration.SecurityTokenHandlers
                     where handler is Microsoft.IdentityModel.Tokens.EncryptedSecurityTokenHandler
                     select handler).First() as Microsoft.IdentityModel.Tokens.EncryptedSecurityTokenHandler;
    
            _configuration.ServiceTokenResolver = encryptedSecurityTokenHandler.Configuration.ServiceTokenResolver =
                    System.IdentityModel.Selectors.SecurityTokenResolver.CreateDefaultSecurityTokenResolver(certificates.AsReadOnly(), false);
        }