【问题标题】:Get subject DN from clients certificate in Go gRPC handler从 Go gRPC 处理程序中的客户端证书获取主题 DN
【发布时间】:2024-01-24 00:26:02
【问题描述】:

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

有可能吗?

【问题讨论】:

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


    【解决方案1】:

    您可以使用ctx context.Context 中的peer.Peer 访问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.Namedocs 写:

    Name 表示 X.509 专有名称

    我使用了来自 answer 的代码,效果很好。

    【讨论】: