yats.git

ref: 2d4a212ce884660f85b47f26a0dd22feb232b207

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
package grpc

import (
	"context"
	"crypto/x509"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/peer"
)

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)
	}
	panic("Could not extract common name")
}

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