title: saml token resolver unable to resolve token reference
body: <p>I am currently working on a small ASP.NET project involving authentication of users against a 3rd party identity provider. I am having problems with SP-initiated SLO requests.</p>
  
  <p>I am using the <a href="http://blogs.msdn.com/b/card/archive/2011/05/16/announcing-the-wif-extension-for-saml-2-0-protocol-community-technology-preview.aspx" rel="nofollow">WIF SAML 2.0 extension</a> to handle the SAML protocol.</p>
  
  <p>When debugging my application it crashes immediately, giving me the following error message (I removed the value of RawData, the public key of the X509Certificate used for signing):</p>
  
  <pre><code>The token resolver is unable to resolve the token reference 'SecurityKeyIdentifier
     (
     IsReadOnly = False,
     Count = 1,
     Clause[0] = X509RawDataKeyIdentifierClause(RawData = )
     )
  '.
  
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
  
  Exception Details: System.InvalidOperationException: The token resolver is unable to resolve the token reference 'SecurityKeyIdentifier
     (
     IsReadOnly = False,
     Count = 1,
     Clause[0] = X509RawDataKeyIdentifierClause(RawData = )
     )
  '.
  
  Source Error: 
  
  An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
  
  Stack Trace: 
  
  
  [InvalidOperationException: The token resolver is unable to resolve the token reference 'SecurityKeyIdentifier
      (
      IsReadOnly = False,
      Count = 1,
      Clause[0] = X509RawDataKeyIdentifierClause(RawData = )
      )
  '.]
     System.IdentityModel.Selectors.SecurityTokenResolver.ResolveToken(SecurityKeyIdentifier keyIdentifier) +226933
     Microsoft.IdentityModel.Web.Saml2AuthenticationModule.ReadSelfMetadata(Stream stream, String fileName, String&amp; entityId, EndpointConfiguration&amp; endpointConfiguration, Boolean&amp; signAuthenticationRequests, X509Certificate2&amp; signingCertificate) +771
  
  [ConfigurationErrorsException: ID4451: The signing key specified in metadata could not be found.  Update the key identifier in metadata or ensure the key is present in the ServiceTokenResolver.  See the inner exception for more details.]
     Microsoft.IdentityModel.Web.Saml2AuthenticationModule.ReadSelfMetadata(Stream stream, String fileName, String&amp; entityId, EndpointConfiguration&amp; endpointConfiguration, Boolean&amp; signAuthenticationRequests, X509Certificate2&amp; signingCertificate) +940
     Microsoft.IdentityModel.Web.Saml2AuthenticationModule..ctor() +606
  
  [TargetInvocationException: Exception has been thrown by the target of an invocation.]
     System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean&amp; canBeCached, RuntimeMethodHandleInternal&amp; ctor, Boolean&amp; bNeedSecurityCheck) +0
     System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
     System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
     System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
     System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +1136
     System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) +111
     System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture) +23
     System.Web.HttpRuntime.CreateNonPublicInstance(Type type, Object[] args) +60
     System.Web.HttpApplication.BuildIntegratedModuleCollection(List`1 moduleList) +231
     System.Web.HttpApplication.GetModuleCollection(IntPtr appContext) +1365
     System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +95
     System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +194
     System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +339
     System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +253
  
  [HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
     System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9090876
     System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
     System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +256
  </code></pre>
  
  <hr>
  
  <p>My SP metadata is as follows:</p>
  
  <pre><code>&lt;md:EntityDescriptor
    xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
    xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
    entityID="urn:mace:feide.no:services:no.ntnu.test_lesesalplass"&gt;
  
  &lt;!--Find where to turn off LogOutRequestSigning!--&gt;
    &lt;md:SPSSODescriptor
       WantAssertionsSigned="false" 
       AuthnRequestsSigned="false"
       protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol"&gt;
  
      &lt;md:KeyDescriptor use="signing"&gt;
        &lt;ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"&gt;
          &lt;ds:X509Data&gt;
            &lt;ds:X509Certificate&gt;
              [...]
            &lt;/ds:X509Certificate&gt;
          &lt;/ds:X509Data&gt;
        &lt;/ds:KeyInfo&gt;
      &lt;/md:KeyDescriptor&gt;
  
      &lt;md:KeyDescriptor use="encryption"&gt;
        &lt;ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"&gt;
          &lt;ds:X509Data&gt;
            &lt;ds:X509Certificate&gt;
              [...]
            &lt;/ds:X509Certificate&gt;
          &lt;/ds:X509Data&gt;
        &lt;/ds:KeyInfo&gt;
      &lt;/md:KeyDescriptor&gt;
  
      &lt;md:NameIDFormat&gt;
        urn:oasis:names:tc:SAML:2.0:nameid-format:transient
      &lt;/md:NameIDFormat&gt;
  
      &lt;md:SingleLogoutService
        Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
        Location="http://localhost:52681/LeseSalReg/saml/redirect/slo"
        ResponseLocation="http://localhost:52681/LeseSalReg/saml/redirect/sloresponse"
        /&gt;
  
      &lt;md:AssertionConsumerService
        isDefault="true" index="0"
        Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
        Location="http://localhost:52681/LeseSalReg/saml/post/ac" 
        /&gt;
  
    &lt;/md:SPSSODescriptor&gt;
  &lt;/md:EntityDescriptor&gt;
  </code></pre>
  
  <hr>
  
  <p>My web.config looks like the following:</p>
  
  <pre><code>&lt;?xml version="1.0"?&gt;
  
  &lt;configuration&gt;
  
    &lt;configSections&gt;
      &lt;section name="microsoft.identityModel" type="Microsoft.IdentityModel.Configuration.MicrosoftIdentityModelSection, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /&gt;
      &lt;section name="microsoft.identityModel.saml" type="Microsoft.IdentityModel.Web.Configuration.MicrosoftIdentityModelSamlSection, Microsoft.IdentityModel.Protocols"/&gt;
    &lt;/configSections&gt;
  
    &lt;connectionStrings&gt;
      &lt;add name="ApplicationServices"
           connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
           providerName="System.Data.SqlClient" /&gt;
      &lt;add name="StudySpaceRegEntities"
           connectionString="metadata=res://*/LeseSalRegEntity.csdl|res://*/LeseSalRegEntity.ssdl|res://*/LeseSalRegEntity.msl;provider=System.Data.SqlClient;provider connection string=&amp;quot;data source=MATSHO;initial catalog=StudySpaceReg;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&amp;quot;"
           providerName="System.Data.EntityClient" /&gt;
    &lt;/connectionStrings&gt;
  
    &lt;system.web&gt;
  
      &lt;compilation debug="true" targetFramework="4.0" &gt;
        &lt;assemblies&gt;
          &lt;add assembly="Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /&gt;
        &lt;/assemblies&gt;
      &lt;/compilation&gt;
  
      &lt;siteMap enabled="false"&gt;
        &lt;providers&gt;
          &lt;clear/&gt;
          &lt;add name="AspNetXmlSiteMapProvider" type="System.Web.XmlSiteMapProvider" siteMapFile="Web.sitemap" securityTrimmingEnabled="true" /&gt;
        &lt;/providers&gt;
      &lt;/siteMap&gt;
  
      &lt;authentication mode="Forms"&gt;
        &lt;forms loginUrl="~/About.aspx" timeout="2880" defaultUrl="~/Register.aspx" /&gt;
      &lt;/authentication&gt;
  
      &lt;pages controlRenderingCompatibilityVersion="4.0" clientIDMode="AutoID" masterPageFile="~/Site.Master"/&gt;
  
      &lt;membership&gt;
        &lt;providers&gt;
          &lt;clear/&gt;
          &lt;add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
               enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
               maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
               applicationName="/" /&gt;
        &lt;/providers&gt;
      &lt;/membership&gt;
  
      &lt;profile&gt;
        &lt;providers&gt;
          &lt;clear/&gt;
          &lt;add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/&gt;
        &lt;/providers&gt;
      &lt;/profile&gt;
  
      &lt;roleManager enabled="false"&gt;
        &lt;providers&gt;
          &lt;clear/&gt;
          &lt;add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" /&gt;
          &lt;add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" /&gt;
        &lt;/providers&gt;
      &lt;/roleManager&gt;
  
      &lt;httpModules&gt;
        &lt;add name="Saml2AuthenticationModule" type="Microsoft.IdentityModel.Web.Saml2AuthenticationModule"/&gt;
        &lt;add name="SessionAuthenticationModule" type="Microsoft.IdentityModel.Web.SessionAuthenticationModule"/&gt;
      &lt;/httpModules&gt;
    &lt;/system.web&gt;
  
    &lt;system.webServer&gt;
  
      &lt;validation validateIntegratedModeConfiguration="false"/&gt;
      &lt;modules&gt;
        &lt;add name="Saml2AuthenticationModule" type="Microsoft.IdentityModel.Web.Saml2AuthenticationModule"/&gt;
        &lt;add name="SessionAuthenticationModule" type="Microsoft.IdentityModel.Web.SessionAuthenticationModule"/&gt;
      &lt;/modules&gt;
  
    &lt;/system.webServer&gt;
  
    &lt;microsoft.identityModel&gt;
      &lt;service&gt;
  
        &lt;audienceUris&gt;
          &lt;clear/&gt;
          &lt;add value="urn:mace:feide.no:services:no.ntnu.test_lesesalplass"/&gt;
        &lt;/audienceUris&gt;
  
        &lt;issuerNameRegistry type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry"&gt;
          &lt;trustedIssuers&gt;
            &lt;add name="https://idp-test.feide.no" thumbprint="fa982efdb69f26e8073c8f815a82a0c5885960a2"/&gt;
          &lt;/trustedIssuers&gt;
        &lt;/issuerNameRegistry&gt;
  
        &lt;securityTokenHandlers&gt;
          &lt;remove type="Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /&gt;
          &lt;add type="Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /&gt;
  
          &lt;remove type="Microsoft.IdentityModel.Tokens.X509SecurityTokenHandler, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/&gt;
          &lt;add type="Microsoft.IdentityModel.Tokens.X509SecurityTokenHandler, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /&gt;
  
          &lt;securityTokenHandlerConfiguration saveBootstrapTokens="true" &gt;
            &lt;audienceUris mode="Always" /&gt;
          &lt;/securityTokenHandlerConfiguration&gt;
        &lt;/securityTokenHandlers&gt;
      &lt;/service&gt;
    &lt;/microsoft.identityModel&gt;
  
    &lt;microsoft.identityModel.saml metadata="App_Data\SPmeta.xml"&gt;
      &lt;identityProviders&gt;
        &lt;metadata file="App_Data\IdPmeta.xml"/&gt;
      &lt;/identityProviders&gt;
    &lt;/microsoft.identityModel.saml&gt;
  </code></pre>
  
  <p>If I comment out the KeyDescriptor for the signing certificate in the SP metadata, the application does not crash. However, when I try to logout I get the following exception:</p>
  
  <blockquote>
    <p>ID4450: Messages of type 'LogoutRequest' must be signed before being sent. Set the message's SigningCredentials property, or configure the Saml2MessageDecorator with a non-null X509Certificate2.</p>
  </blockquote>
  
  <p>I don't think WIF supports un-signed SLO requests, so I have to sign them. For reasons I fail to comprehend, it seems the SecurityTokenResolver is not able to parse the X509Certificate used for signing defined in the metadata.</p>
  
  <p>Any pointers will be deeply appreciated.</p>