从Go gRPC处理程序中的客户端证书中获取主题DN

时间:2017-11-09 06:58:40

标签: go ssl-certificate tls1.2 grpc mutual-authentication

我正在使用相互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?
    // ...
}

有可能吗?

1 个答案:

答案 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的代码,并且它很有用。