package grpc import ( "context" "crypto/x509" "errors" "google.golang.org/grpc/credentials" "google.golang.org/grpc/peer" ) // For grpc TLS client implementation, see: // https://medium.com/@mertkimyonsen/securing-grpc-connection-with-ssl-tls-certificate-using-go-db3852fe89dd func GetClientCN(ctx context.Context) (string, error) { peerInfo, ok := peer.FromContext(ctx) if !ok { return "", errors.New("could not extract common name: missing peer information") } tlsInfo, ok := peerInfo.AuthInfo.(credentials.TLSInfo) if !ok { return "", errors.New("could not extract common name: peer is not using TLS") } certificates := tlsInfo.State.PeerCertificates if len(certificates) == 0 { return "", errors.New("could not extract common name: missing peer certificate") } return extractCommonName(certificates), nil } func extractCommonName(certificates []*x509.Certificate) string { if len(certificates) > 0 { return certificates[0].Subject.CommonName } panic("Could not extract common name") }