yats.git

ref: 9a66d445db43a461cfe9fe14c95babf175007b03

server/grpc/grpc-tls.go


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package grpc

import (
	"context"
	"crypto/x509"
	"fmt"
	"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 {
	peers, ok := peer.FromContext(ctx)
	if ok {
		tlsInfo := peers.AuthInfo.(credentials.TLSInfo)
		certificates := tlsInfo.State.PeerCertificates
		//v := tlsInfo.State.VerifiedChains[0][0].Subject.CommonName
		//fmt.Printf("%v - %v\n", peers.Addr.String(), v)
		return extractCommonName(certificates)
	}
	fmt.Println("Could not extract common name")
	return ""
}

func extractCommonName(certificates []*x509.Certificate) string {
	if len(certificates) > 0 {
		return certificates[0].Subject.CommonName
	}
	fmt.Println("Could not extract common name")
	return ""
}