gRPC:如何在客户端配置 SSL?

SOW*_*G M 6 java ssl netty grpc grpc-java

它对我来说是新话题。我能够以明文形式连接。

public ManagedChannel getChannel(String serviceName){
    TSServiceClientManager scm = TSServiceManagementFactory.getInstance().getServiceClientManager();
    TSServiceConnectionInfo connInfo = scm.getServiceConnectionInfo(serviceName);
    if(channel == null){
        channel = ManagedChannelBuilder.forAddress(connInfo.getHost(), connInfo.getPort())
                .usePlaintext(true) //need help here for SSL code 
                .build();
    }

    return channel;
}
Run Code Online (Sandbox Code Playgroud)

我被告知要启用客户端 SSL。我知道如何生成密钥库、信任库、pem、CA 等。我需要以下方面的帮助:

如何启用 SSL 而不是 .usePlaintext(true) 如上面的代码所示?

(考虑到证书文件、密钥库、信任库和 .pem 文件存在,请重写代码)

我想知道与服务器有什么关系才能使 SSL 连接正常工作?

Eri*_*son 6

您需要使用特定于传输的 API。您今天可能正在使用 Netty。对于 Netty,需要配置 Netty 的 SslContext 并传递给 gRPC。您的用法可能如下所示:

SslContext sslcontext = GrpcSslContexts.forClient()
    // if server's cert doesn't chain to a standard root
    .trustManager(caFile)
    .keyManager(clientCertFile, keyFile) // client cert
    .build();
channel = NettyChannelBuilder.forAddress(serverHost, serverPort)
    .sslContext(sslContext)
    .build();
Run Code Online (Sandbox Code Playgroud)

如果您需要服务器端配置,它将使用类似的NettyServerBuilder.sslContext(). 但是上下文本身会有所不同。