【问题标题】:Failure validating SAML 2 assertion using Windows Identity Foundation使用 Windows Identity Foundation 验证 SAML 2 断言失败
【发布时间】:2016-09-15 16:34:58
【问题描述】:

我正在尝试用我没有经验的 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>

我想我在配置中遗漏了一些东西,所以我根据this question 中的信息插入了更改。然而,这并没有改变我的结果。

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

【问题讨论】:

  • 不打印异常。仅消息。请打印出整个 exception.ToString() 以获取更多详细信息。基于此,也许有人可以为您提供更多帮助:)
  • @Thuan - 感谢您的建议。添加了上面的新信息。
  • 您真的需要替换这个模块还是要对 IIS 应用程序或类似的东西进行身份验证?
  • @TGlatzer - 自定义模块不受支持。即使它有效,我也不会被允许将其投入生产。
  • 问题更多:为什么需要这样的模块? IIS 可以为您完成所有繁重的工作。

标签: c# saml-2.0 wif


【解决方案1】:

WIF 签名验证的一个非常烦人的问题是它使用了不支持跟踪的 SignedXml 的内部实现。作为记录,公共 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

【讨论】:

  • 哇。很简单。我遵循了 SignedXml 示例。 5行代码就搞定了。谢谢!
  • +1 指出 空格对于签名验证很重要XmlReader 默认为去除空格,因此请确保在 XmlReaderSettings 上设置 IgnoreWhitespace = true
【解决方案2】:

看看active-directory-dotnet-webapp-wsfederation

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

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

【讨论】:

  • 这是 WS-Fed 的“不”。另外,我试图不干扰将断言交给我进行验证的界面。
猜你喜欢
  • 2018-11-09
  • 2012-12-26
  • 2011-02-06
  • 2019-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
相关资源
最近更新 更多