首页 > 解决方案 > 使用 c# 连接 AWS cassandra

问题描述

我正在尝试使用以下代码连接到 AWS Cassandra:

       var pathToCAFile = $"{Directory.GetCurrentDirectory()}/AmazonRootCA1.pem";
        X509Certificate2[] certs = new X509Certificate2[] { new X509Certificate2(pathToCAFile, "amazon") };
        X509Certificate2Collection certificateCollection = new X509Certificate2Collection(certs);
        var options = new Cassandra.SSLOptions(SslProtocols.Tls11, true, ValidateServerCertificate);
        options.SetCertificateCollection(certificateCollection);
        Cluster cluster = Cluster
                            .Builder()
                            .WithCredentials("username", "password")
                            .WithPort(9142)
                            .AddContactPoint("cassandra.us-east-1.amazonaws.com")
                           .WithSSL()
                            .WithLoadBalancingPolicy(new DefaultLoadBalancingPolicy("us-east-1"))
                            .Build();

        // Connect to the nodes using a keyspace
        var session = cluster.Connect("system_distributed");

 

        // Execute a query on a connection synchronously
        var rs = session.Execute("select * from system.peers");

这是我得到的错误:

“Cassandra.NoHostAvailableException:'所有主机尝试查询失败(尝试 3.83.169.143:9142:AuthenticationException '远程证书根据验证过程无效。')'

此异常最初是在此调用堆栈中引发的:

Cassandra.Connections.Control.ControlConnection.Connect(bool) System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task) System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult() Cassandra.Connections.Control.ControlConnection.InitAsync() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices。 TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task) System.Runtime.CompilerServices.ConfiguredTaskAwaitable。ConfiguredTaskAwaiter.GetResult() ... [调用堆栈被截断]

标签: c#amazon-web-servicescassandra

解决方案


我假设您使用的是 DataStax C# 驱动程序。如果是这种情况,则有关于 SSL/TLS 的文档部分,其中还包含几个示例的链接:https ://docs.datastax.com/en/developer/csharp-driver/3.15/features/tls/

如果该片段是准确的,那么您实际上并没有设置SSLOptions方法Builder.WithSSL()

如果这不起作用并且代码示例对您没有帮助,请向我们展示该ValidateServerCertificate方法,以便我们查看证书验证可能出现的问题。


编辑(来自我下面的评论):

TLS/SSL 文档页面上,有一个与此处相关的部分:使用自定义根证书启用服务器身份验证

如文档中所述,您要么必须在运行应用程序的机器上安装该证书,要么必须提供与此类似的自定义证书验证器。

SSLOptions.SetCertificateCollection()方法用于客户端身份验证,因此对于您需要服务器身份验证的情况没有用处。


推荐阅读