使用 Windows Identity Foundation 验证 SAML 2 断言失败

Failure validating SAML 2 assertion using Windows Identity Foundation

我正在尝试用我没有经验的 WIF 替换我没有源代码的自定义 SAML 2 库。我没有找到示例代码的运气,所以我采用试错法。代码似乎几乎可以工作,但我收到了一条非常简洁的 The signature verification failed. 消息,除此之外什么都没有。

对于此过程的输入,我有一个 X509 证书和一个 base-64 编码的 SAML 2 断言。

我的代码是;

// Load X509 certificate
string rootPath = System.AppDomain.CurrentDomain.BaseDirectory;
string certFilePath = ConfigurationManager.AppSettings["SAMLCertLocation"];
certFilePath = Path.Combine(rootPath, certFilePath);
msg = string.Format("SAMLCertLocation: [{0}]", certFilePath);
Trace.TraceInformation(msg);
X509Certificate2 cert = new X509Certificate2(certFilePath, String.Empty);

// build token handler configuration
List<System.IdentityModel.Tokens.SecurityToken> serviceTokens = new List<System.IdentityModel.Tokens.SecurityToken>();
serviceTokens.Add(new System.IdentityModel.Tokens.X509SecurityToken(cert));

ConfigurationBasedIssuerNameRegistry issuers = new ConfigurationBasedIssuerNameRegistry();
issuers.AddTrustedIssuer(cert.Thumbprint, cert.Issuer);

SecurityTokenHandlerConfiguration config = new SecurityTokenHandlerConfiguration()
{
    AudienceRestriction = { AudienceMode = AudienceUriMode.Never },
    CertificateValidator = X509CertificateValidator.None,            
    // RevocationMode = X509RevocationMode.NoCheck,             // no such property
    IssuerNameRegistry = issuers,
    MaxClockSkew = TimeSpan.FromMinutes(5),
    ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(serviceTokens.AsReadOnly(), false)
};

// extract the assertion from the request
byte[] data = Convert.FromBase64String(reqstr);
string assertion = Encoding.UTF8.GetString(data);
Trace.TraceInformation(assertion);

// read and validate the assertion
Saml2SecurityTokenHandler handler = new Saml2SecurityTokenHandler();
handler.Configuration = config;
bool canReadToken = handler.CanReadToken(XmlReader.Create(new StringReader(assertion)));
msg = string.Format("CanReadToken [{0}]", canReadToken);
Trace.TraceInformation(msg);
if (canReadToken)
{
    try
    {
        System.IdentityModel.Tokens.SecurityToken token = handler.ReadToken(XmlReader.Create(new StringReader(assertion)));
        ClaimsIdentityCollection claims = handler.ValidateToken(token);
        msg = string.Format("SAML Claims [{0}]", claims.ToString());
        Trace.TraceInformation(msg);
    }
    catch (Exception e)
    {
        msg = string.Format("Validation Exception [{0}]", e.Message);
        Trace.TraceInformation(msg);
    }
}

我得到的错误是;

2016-09-15T19:34:39  PID[6504] Information CanReadToken [True]
2016-09-15T19:34:39  PID[6504] Information Validation Exception [ID6013: The signature verification failed.]
2016-09-19T13:13:13  PID[11912] Information Validation Exception [System.Security.Cryptography.CryptographicException: ID6013: The signature verification failed.
    at Microsoft.IdentityModel.Protocols.XmlSignature.SignedXml.VerifySignature(HashAlgorithm hash, AsymmetricSignatureDeformatter deformatter, String signatureMethod)
    at Microsoft.IdentityModel.Protocols.XmlSignature.SignedXml.StartSignatureVerification(SecurityKey verificationKey)
    at Microsoft.IdentityModel.Protocols.XmlSignature.EnvelopedSignatureReader.OnEndOfRootElement()
    at Microsoft.IdentityModel.Protocols.XmlSignature.EnvelopedSignatureReader.Read()
    at System.Xml.XmlReader.ReadEndElement()
    at Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.ReadAssertion(XmlReader reader)
    at Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.ReadToken(XmlReader reader)
    at AXAWeb.Code.Saml20Login.Saml20Login.SamlLogon(String samlString, String absoluteUrl) in Saml20Login.cs:line 189]

断言的签名部分是这样的;

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
  <SignedInfo>
    <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
    <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
    <Reference URI="#SAML-a964f232-77ab-40d1-a74a-f85dfe10f57d">
      <Transforms>
        <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
        <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
      </Transforms>
      <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
      <DigestValue>B9q+BrqH+Fq74R8eCqd+Vd+vKkw=</DigestValue>
    </Reference>
  </SignedInfo>
  <SignatureValue>...snip for brevity...</SignatureValue>
  <KeyInfo>
    <X509Data>
      <X509Certificate>...snip for brevity...</X509Certificate>
    </X509Data>
    <X509Data>
      <X509IssuerSerial>
        <X509IssuerName>CN=Entrust Certification Authority - L1K, OU="(c) 2012 Entrust, Inc. - for authorized use only", OU=See www.entrust.net/legal-terms, O="Entrust, Inc.", C=US</X509IssuerName>
        <X509SerialNumber>1356031830</X509SerialNumber>
      </X509IssuerSerial>
    </X509Data>
  </KeyInfo>
</Signature>

我预计我在配置中遗漏了一些东西,所以我根据 中的信息插入了更改。但是,它并没有改变我的结果。

有经验的人知道我需要添加什么才能完成这项工作吗?

看看active-directory-dotnet-webapp-wsfederation

基本上撕掉 SAMl 的东西并使用 OWIN Nuget Ws-Fed 包。

当然,这是假设您的 IDP 支持 WS-FEd?

WIF 签名验证的一个非常烦人的问题是它使用不支持跟踪的 SignedXml 内部实现。作为记录,public System.Security.Cryptography.Xml.SignedXml 支持跟踪,因此更容易找出问题所在。无论如何,根据我的经验,我建议您检查您的断言 xml 是否包含空格。如果是,则在将其读入 XmlReader 时需要使用 PreserveWhiteSpaces 设置。

已编辑:另外两件要检查的事情是,您是否连接了正确的证书来验证签名,以及您是否可以使用 System.Security.Cryptography.Xml.SignedXml 来验证断言的签名:https://msdn.microsoft.com/en-us/library/ms229950(v=vs.110).aspx