如何检查http-redirect samlresponse uri request

时间:2016-06-27 12:29:14

标签: c# saml-2.0

我在http-get中分别获取了xml,signature和signature-algoirthm。 那么,我该如何处理此问题以验证签名?

目前我的代码是:

public void CheckSignature(string response, string sig, string sigalg, byte[] cert) 
{
    Log("loading cert");
    X509Certificate2 cert2 = new X509Certificate2(cert);

    bool result = false;

    /* response, sigalg and sig are url-decoded or not, doesn't matter :( */
    Log("first variant");
    var signedString = string.Format(CultureInfo.InvariantCulture, "SAMLResponse={0}&SigAlg={1}", response, sigalg);
    result = DoCheck(signedString, sigalg, sig, cert2);

    Log("2nd variant");
    signedString = string.Format(CultureInfo.InvariantCulture, "SAMLResponse={0}", response);
    result = DoCheck(signedString, sigalg, sig, cert2);


    Log("3rd variant");
    signedString = string.Format(CultureInfo.InvariantCulture, "{0}", response);
    result = DoCheck(signedString, sigalg, sig, cert2); 
}

private bool DoCheck(string signedString, string sigalg, string sig, X509Certificate2 cert2) 
{
    try {
        var sigDescription = (SignatureDescription)CryptoConfig.CreateFromName(sigalg);
        var hashAlg = sigDescription.CreateDigest();
        //why is this needed?
        hashAlg.ComputeHash(Encoding.UTF8.GetBytes(signedString));

        var signature = Convert.FromBase64String(sig);

        Log("trying to verify::" +  signedString + Environment.NewLine);

        X509AsymmetricSecurityKey key = new X509AsymmetricSecurityKey(cert2);
        AsymmetricAlgorithm asym_alg = key.GetAsymmetricAlgorithm(sigalg, false);
        AsymmetricSignatureDeformatter def = sigDescription.CreateDeformatter(asym_alg);


        bool result = false;
        result = def.VerifySignature(hashAlg, signature);
        //sadly always false.
        Log("woop woop:" + result);
        return result;
    }
    catch (Exception ex) {
        Log(ex.Message);
        Log(ex.StackTrace);
    }
    return false;
}

但是现在,无论我做什么,结果总是假的。 基于https://github.com/KentorIT/authservices/blob/master/Kentor.AuthServices/WebSSO/Saml2RedirectBinding.cs

2 个答案:

答案 0 :(得分:0)

如果您在表单SAMLResponse=....SigAlg=...Signature=...(第一个参数也可以是SAMLRequest)上获得查询字符串,则表示您正在使用SAML2 HTTP重定向绑定获取消息。有关其工作原理的说明,请参阅SAML2 Specification。具体来说,您应该阅读绑定规范。

或者,如果您想节省大量工作,请找到要使用的现有SAML2实现。 C#有几种开源实现方式。

答案 1 :(得分:0)

那么,

我自己发现了。 这确实是rawrequest参数的问题。 (我的代码已经解析了它,但无论如何它都会失败)

// Can't use the query string params as found in HttpReqeustData
// because they are already unescaped and we need the exact format
// of the original data.
        var rawQueryStringParams = request.Url.Query.TrimStart('?')
            .Split('&')
            .Select(qp => qp.Split('='))
            .ToDictionary(kv => kv[0], kv => kv[1]);