Using TLS in grpc-gateway

Mayank dixit
Average problems quick solutions
1 min readNov 30, 2018

--

In GRPC client

By default DialOption{grpc.WithInsecure()} is used in example (point 6). As mention in docs you just need to replace WithInsecure with transport creds.

//opts := []grpc.DialOption{grpc.WithInsecure()}
creds, _ := credentials.NewClientTLSFromFile("tls.crt", "")
opts := []grpc.DialOption{grpc.WithTransportCredentials(creds)}

In HTTP server

Replace ListenAndServe to ListenAndServeTLS

Full example:

func run() error {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
mux := runtime.NewServeMux()
// opts := []grpc.DialOption{grpc.WithInsecure()}
creds, err := credentials.NewClientTLSFromFile("tls.crt", "")
if err != nil {
return err
}
opts := []grpc.DialOption{grpc.WithTransportCredentials(creds)}
err = fw.RegisterUserServiceHandlerFromEndpoint(ctx, mux, *grpcTarget, opts)
if err != nil {
return err
}
return http.ListenAndServeTLS(*hostAddr, "tls.crt", "tls.key", mux)
}

That’s it. Cheers!

PS: gist

--

--

Mayank dixit
Average problems quick solutions

Web & open source enthusiast. Interested in #code #comedy #music and #kitchen. Learns, writes and shares tech stuff. Wannabe product guy.