forked from sonic-net/sonic-gnmi
/
clientCertAuth.go
41 lines (34 loc) · 1.24 KB
/
clientCertAuth.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
34
35
36
37
38
39
40
41
package gnmi
import (
"github.com/sonic-net/sonic-gnmi/common_utils"
"github.com/golang/glog"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
)
func ClientCertAuthenAndAuthor(ctx context.Context) (context.Context, error) {
rc, ctx := common_utils.GetContext(ctx)
p, ok := peer.FromContext(ctx)
if !ok {
return ctx, status.Error(codes.Unauthenticated, "no peer found")
}
tlsAuth, ok := p.AuthInfo.(credentials.TLSInfo)
if !ok {
return ctx, status.Error(codes.Unauthenticated, "unexpected peer transport credentials")
}
if len(tlsAuth.State.VerifiedChains) == 0 || len(tlsAuth.State.VerifiedChains[0]) == 0 {
return ctx, status.Error(codes.Unauthenticated, "could not verify peer certificate")
}
var username string
username = tlsAuth.State.VerifiedChains[0][0].Subject.CommonName
if len(username) == 0 {
return ctx, status.Error(codes.Unauthenticated, "invalid username in certificate common name.")
}
if err := PopulateAuthStruct(username, &rc.Auth, nil); err != nil {
glog.Infof("[%s] Failed to retrieve authentication information; %v", rc.ID, err)
return ctx, status.Errorf(codes.Unauthenticated, "")
}
return ctx, nil
}