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

时间:2016-09-15 16:34:58

标签: c# saml-2.0 wif

我试图用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中的信息插入了更改。但是,它并没有改变我的结果。

有经验的人是否知道我需要添加什么来使其工作?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

查看active-directory-dotnet-webapp-wsfederation

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

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

相关问题