.NET核心自定义服务器证书CA.

时间:2018-06-09 01:02:43

标签: c# .net validation kubernetes x509certificate

我想从群集外的.NET Core应用程序调用Kubernetes API。

我有一个带有HttpClientHandler的HttpClient,我设置此回调以忽略无效(不受信任)的证书并且它可以工作:

handler.ServerCertificateCustomValidationCallback +=
    (message, certificate, chain, errors) => true;

但是在kubectl的kubeconfig中,我有这个:

...
clusters:
- cluster:
    certificate-authority-data: SOME_AUTHORITY_DATA
    server: https://myserver.io:443
...

如何在我的应用程序中使用 certificate-authority-data 验证服务器证书?

1 个答案:

答案 0 :(得分:1)

private static byte[] s_issuingCABytes = { ... };

handler.ServerCertificateCustomValidationCallback +=
    (message, certificate, chain, errors) =>
    {
        const SslPolicyErrors Mask =
#if CA_IS_TRUSTED
            ~SslPolicyErrors.None;
#else
            ~SslPolicyErrors.RemoteCertificateChainErrors;
#endif

        // If a cert is not present, or it didn't match the host.
        // (And if the CA should have been root trusted anyways, also checks that)
        if ((errors & Mask) != SslPolicyErrors.None)
        {
            return false;
        }

        foreach (X509ChainElement element in chain.ChainElements)
        {
            if (element.Certificate.RawData.SequenceEqual(s_issuingCABytes))
            {
                // The expected certificate was found, huzzah!
                return true;
            }
        }

        // The expected cert was not in the chain.
        return false;
    };
相关问题