从 Go gRPC 处理程序中的客户端证书获取主题 DN [英] Get subject DN from clients certificate in Go gRPC handler

查看:59
本文介绍了从 Go gRPC 处理程序中的客户端证书获取主题 DN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有相互 tls 的 Golang gRPC.是否可以通过 rpc 方法获取客户端的证书主题 DN?

I'm using Golang gRPC with mutual tls. Is it possible to get client's certificate subject DN from rpc method?

// ...
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?
    // ...
}

有可能吗?

推荐答案

您可以使用 ctx context.Context 中的 peer.Peer 来访问<中的 OID 注册表代码>x509.Certificate.

You can use peer.Peer from ctx context.Context for access to the OID registry in x509.Certificate.

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 专有名称

Name represents an X.509 distinguished name

我使用了来自这个answer的代码,而且效果很好.

And I used code from this answer and it well work.

这篇关于从 Go gRPC 处理程序中的客户端证书获取主题 DN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆