Golang 的 LDAP 客户端库如何处理证书?

How does Golang's LDAP client library work with certificates?

我正在尝试连接到 G Suite's LDAPS server with Golang's LDAP library

但是,在example中,有两件事我不是很明白。

  1. 好像是先通过非加密的LDAP连接?然后升级?是这样吗,如果是这样,我不能从连接加密开始吗?

  2. Google 提供了一个 .cer 和 .key 文件来连接到他们的 ldap 服务器。我看不到它在哪里使用这些文件。我确实在他们的文档中看到很多 LDAP 客户端需要将文件组合成 .p12。 Go 有必要吗?

如果回答此问题的人可以提供示例,那将非常有帮助。谢谢。

正如您所指出的,

StartTLS 允许升级连接以在连接生命周期的后期使用 TLS

如果您想立即通过 TLS 连接,请使用众所周知的 ldaps 端口 636(而不是 389)- 并使用 DialTLS:

// l, err := ldap.Dial("tcp", "ldap.example.com:389"))

var tlsConf *tls.Config

ldaps, err := ldap.DialTLS("tcp", "gsuite.google.com:636", tlsConf)

您也可以使用 DialURL 来根据模式推断 TLS 或非 TLS,例如

conn, err := ldap.DialURL("ldap://ldap.example.com") // non-TLS on default port 389
conn, err := ldap.DialURL("ldaps://ldap.example.com") // TLS on default port 636
conn, err := ldap.DialURL("ldaps://myserver.com:1234") // TLS on custom port 1234

// Note: there is no way to add a custom tls.Config with this method

因此,如果使用 DialTLS:因为您使用的是 Google 服务,它的信任证书应该已经在您的钥匙串中,所以一个简单的 tls.Config 就足够了:

tlsConf = &tls.Config{ServerName:"gsuite.google.com"} // <- ensure this matches the hostname provided by the server

如果你想准备 运行 进行测试:

// DONT EVER USE THIS IN PRODUCTION...
tlsConf = &tls.Config{InsecureSkipVerify: true} // DO NOT USE EVER

为客户端身份验证添加客户端证书:

// Load cer & key files into a pair of []byte 
cert, err := tls.X509KeyPair(cer, key)
if err != nil {
    log.Fatal(err)
}
tlsCong := &tls.Config{Certificates: []tls.Certificate{cert}}