gRPC authentication

Secure gRPC connections in Go by configuring TLS credentials using the grpc/credentials package for both clients and servers.

gRPC authentication in Go is handled by configuring TLS and attaching credentials to the client or server connection using the google.golang.org/grpc/credentials package. For a secure client connection, create a grpc.Dial call with grpc.WithTransportCredentials set to credentials.NewClientTLSFromCert or credentials.NewTLS with your certificate configuration.

import (
    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials"
)

// Create a secure client connection
conn, err := grpc.Dial("localhost:50051",
    grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),
)
if err != nil {
    log.Fatalf("did not connect: %v", err)
}
defer conn.Close()

For a server, pass grpc.Creds to grpc.NewServer using credentials.NewServerTLSFromFile or credentials.NewTLS with your server certificate and key.

import (
    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials"
)

// Create a secure server
creds, err := credentials.NewServerTLSFromFile("server.crt", "server.key")
if err != nil {
    log.Fatalf("Failed to generate credentials: %v", err)
}

lis, err := net.Listen("tcp", ":50051")
if err != nil {
    log.Fatalf("failed to listen: %v", err)
}

s := grpc.NewServer(grpc.Creds(creds))
// Register your service here
// s.RegisterYourService(&YourServer{})

if err := s.Serve(lis); err != nil {
    log.Fatalf("failed to serve: %v", err)
}