Search code examples
dartsecurityprotocol-buffersgrpccredentials

grpc dart server and client exmple with secure connection


I have searched for grpc secure server and client example in dart I couldn't find any, example of creating insecure connection can be found but this is not what I am looking for.

I have managed to compile it with secure but getting grpc error when connecting between client to server

Caught error: gRPC Error (code: 14, codeName: UNAVAILABLE, message: Error connecting: HandshakeException: Connection terminated during handshake, details: null, rawResponse: null)

My Server credentials implementation:

final String myPath = 'password_file.pem';
final File f = File(myPath);
final Uint8List bytes = f.readAsBytesSync();

final server = Server(
  [myPbServer()],
  const <Interceptor>[],
  CodecRegistry(codecs: const [GzipCodec(), IdentityCodec()]),
);
await server.serve(
  port: 6053,
  security: ServerTlsCredentials(certificate: bytes),
);

My client credentials implementation:

final String myPath = 'password_file.pem';
final File f = File(myPath);
final Uint8List bytes = f.readAsBytesSync();

return channel = ClientChannel(
  deviceIp,
  port: 6053,
  options: ChannelOptions(
    credentials: ChannelCredentials.secure(
      certificates: myPath,
    ),
  ),
);

Can someone answer with working secure grpc server and client example?.


Solution

  • As written in the test cases of grpc-dart

    Server:

    final server = Server([YourServerClass()]);
    await server.serve(
      port: portNumber,
      security: ServerTlsCredentials(
        certificate: File('crtFilePath/file.crt').readAsBytesSync(),
        privateKey: File('keycrtFilePath/file.key').readAsBytesSync(),
      ),
    );
    

    Client:

    import 'package:grpc/src/client/http2_connection.dart';
    
    FixedConnectionClientChannel(
      Http2ClientConnection(
        serverAddress,
        portNumber,
        ChannelOptions(
          credentials: ChannelCredentials.secure(
            certificates: File('crtFilePath/file.crt').readAsBytesSync(),
            authority: 'localhost',
          ),
        ),
      ),
    );
    
    
    class FixedConnectionClientChannel extends ClientChannelBase {
      final Http2ClientConnection clientConnection;
      List<ConnectionState> states = <ConnectionState>[];
      FixedConnectionClientChannel(this.clientConnection) {
        clientConnection.onStateChanged = (c) => states.add(c.state);
      }
      @override
      ClientConnection createConnection() => clientConnection;
    }