我正在使用相互tls的Golang gRPC。是否可以从rpc方法获取客户的证书主题DN?
// ...
func main() {
// ...
creds := credentials.NewTLS(&tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
Certificates: []tls.Certificate{certificate},
ClientCAs: certPool,
MinVersion: tsl.VersionTLS12,
})
s := NewMyService()
gs := grpc.NewServer(grpc.Creds(creds))
RegisterGRPCZmqProxyServer(gs, s)
er := gs.Serve(lis)
// ...
}
// ...
func (s *myService) Foo(ctx context.Context, req *FooRequest) (*FooResonse, error) {
$dn := // What should be here?
// ...
}
有可能吗?
答案 0 :(得分:1)
您可以使用peer.Peer
中的ctx context.Context
来访问x509.Certificate
中的OID注册表。
func (s *myService) Foo(ctx context.Context, req *FooRequest) (*FooResonse, error) {
p, ok := peer.FromContext(ctx)
if ok {
tlsInfo := p.AuthInfo.(credentials.TLSInfo)
subject := tlsInfo.State.VerifiedChains[0][0].Subject
// do something ...
}
}
主题是pkix.Name
并且在docs中写道:
Name表示X.509专有名称
我使用了这个answer的代码,并且它很有用。