首页 > 解决方案 > .NET Core 自定义服务器证书 CA

问题描述

我想从集群外的 .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
...

如何在我的应用程序中使用该证书授权数据验证服务器证书?

标签: c#.netvalidationkubernetesx509certificate

解决方案


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;
    };

推荐阅读