How to connect to mongoDB via ssl using .crt file in Go

huangapple go评论119阅读模式
英文:

How to connect to mongoDB via ssl using .crt file in Go

问题

我正在尝试使用.crt文件连接到托管在Azure上的Mongo数据库。

我可以成功地从我的Linux机器终端使用以下命令连接:

  1. mongo mongodb://username:password@prod-replicaset-0.com:27017,prod-replicaset-1.com:27017,prod-replicaset-2.com:27017/ --tls --tlsCAFile rootca.crt --tlsAllowInvalidCertificates

我还可以通过设置"Use SSL protocol"并将认证机制设置为"SCRAM-SHA-256"来从Mongo UI客户端(如Robo3T)连接。
[如果将认证机制设置为其他值,将导致身份验证失败]

但是,我无法在Go语言代码中连接到该数据库。

这是我正在使用的代码示例:

  1. package main
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "io/ioutil"
  6. "log"
  7. "net"
  8. "github.com/globalsign/mgo"
  9. )
  10. func InitMongo() error {
  11. rootCerts := x509.NewCertPool()
  12. ca, err := ioutil.ReadFile("./rootca.crt")
  13. if err != nil {
  14. log.Fatalf("failed to read file : %s", err.Error())
  15. return err
  16. }
  17. success := rootCerts.AppendCertsFromPEM(ca)
  18. if !success {
  19. log.Printf("rootcert failed")
  20. }
  21. connStr := "mongodb://username:password@prod-replicaset-0.com:27017,prod-replicaset-1.com:27017,prod-replicaset-2.com:27017/?ssl=true"
  22. dbDialInfo, err := mgo.ParseURL(connStr)
  23. if err != nil {
  24. log.Fatal("unable to parse url - " + err.Error())
  25. }
  26. dbDialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
  27. return tls.Dial("tcp", addr.String(), &tls.Config{
  28. RootCAs: rootCerts,
  29. InsecureSkipVerify: true,
  30. })
  31. }
  32. // dbDialInfo.Mechanism = "SCRAM-SHA-256"
  33. _session, err := mgo.DialWithInfo(dbDialInfo)
  34. if err != nil {
  35. log.Fatalf("failed to creating db session : %s", err.Error())
  36. return err
  37. }
  38. log.Printf("Created session - %v", _session)
  39. return nil
  40. }

当我运行此代码时,我收到错误消息:
failed to creating db session : "server returned error on SASL authentication step: Authentication failed."

如果在创建会话之前设置[dbDialInfo.Mechanism = "SCRAM-SHA-256"],我收到错误消息:
failed to creating db session : "SASL support not enabled during build (-tags sasl)"

请告诉我是什么原因导致了这个问题,我该如何连接到数据库。
目前我正在使用"github.com/globalsign/mgo",如果需要使用其他库,对我来说完全没问题。
我只想连接到数据库。

rootca.crt文件的内容如下:

  1. -----BEGIN CERTIFICATE-----
  2. MIIGLjCCBBagAwIBAgIUbxINX1qe6W+7kolWGp+MX8NbYj8wDQYJKoZIhvcNAQEL
  3. <blah> <blah> <blah> <blah> <blah> <blah> <blah> <blah> <blah> <blah>
  4. jCZAGGHmbrR3zeIsOY8yKau0IXqRp5Wy6NQ0poOTcma9BfwNUVc4/ixsCkEVYbgW
  5. eMs=
  6. -----END CERTIFICATE-----

谢谢。

英文:

I am trying to connect to a mongo database hosted in azure using the .crt file.

I am successfully able to connect from my linux machine terminal using command:

  1. mongo mongodb://username:password@prod-replicaset-0.com:27017,prod-replicaset-1.com:27017,prod-replicaset-2.com:27017/ --tls --tlsCAFile rootca.crt --tlsAllowInvalidCertificates

I am also able to connect from mongo UI client like robo3T by setting "Use SSL protocol" and using Auth Mechanism as "SCRAM-SHA-256".
[If I set Auth Mechanism to any other value, results in Authentication Failure]

But I am not able to connect to that database in Go lang code.

Here is a sample of code I am using:

  1. package main
  2. import (
  3. &quot;crypto/tls&quot;
  4. &quot;crypto/x509&quot;
  5. &quot;io/ioutil&quot;
  6. &quot;log&quot;
  7. &quot;net&quot;
  8. &quot;github.com/globalsign/mgo&quot;
  9. )
  10. func InitMongo() error {
  11. rootCerts := x509.NewCertPool()
  12. ca, err := ioutil.ReadFile(&quot;./rootca.crt&quot;)
  13. if err != nil {
  14. log.Fatalf(&quot;failed to read file : %s&quot;, err.Error())
  15. return err
  16. }
  17. success := rootCerts.AppendCertsFromPEM(ca)
  18. if !success {
  19. log.Printf(&quot;rootcert failed&quot;)
  20. }
  21. connStr := &quot;mongodb://username:password@prod-replicaset-0.com:27017,prod-replicaset-1.com:27017,prod-replicaset-2.com:27017/?ssl=true&quot;
  22. dbDialInfo, err := mgo.ParseURL(connStr)
  23. if err != nil {
  24. log.Fatal(&quot;unable to parse url - &quot; + err.Error())
  25. }
  26. dbDialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {
  27. return tls.Dial(&quot;tcp&quot;, addr.String(), &amp;tls.Config{
  28. RootCAs: rootCerts,
  29. InsecureSkipVerify: true,
  30. })
  31. }
  32. // dbDialInfo.Mechanism = &quot;SCRAM-SHA-256&quot;
  33. _session, err := mgo.DialWithInfo(dbDialInfo)
  34. if err != nil {
  35. log.Fatalf(&quot;failed to creating db session : %s&quot;, err.Error())
  36. return err
  37. }
  38. log.Printf(&quot;Created session - %v&quot;, _session)
  39. return nil
  40. }

When I run this code, I get error:
failed to creating db session : "server returned error on SASL authentication step: Authentication failed."

If I set [dbDialInfo.Mechanism = "SCRAM-SHA-256"] before creating session, I get error:
failed to creating db session : "SASL support not enabled during build (-tags sasl)"

Please let me know what is causing this issue, how can I connect to the database.
Currently I am using "github.com/globalsign/mgo", if it required to use any other library, that's totally fine for me.
I just want to get connected to the db.

rootca.crt file looks something like:

  1. -----BEGIN CERTIFICATE-----
  2. MIIGLjCCBBagAwIBAgIUbxINX1qe6W+7kolWGp+MX8NbYj8wDQYJKoZIhvcNAQEL
  3. &lt;blah&gt; &lt;blah&gt; &lt;blah&gt; &lt;blah&gt; &lt;blah&gt; &lt;blah&gt; &lt;blah&gt; &lt;blah&gt; &lt;blah&gt;
  4. jCZAGGHmbrR3zeIsOY8yKau0IXqRp5Wy6NQ0poOTcma9BfwNUVc4/ixsCkEVYbgW
  5. eMs=
  6. -----END CERTIFICATE-----

Thank you.

答案1

得分: 0

经过大量研究,我无法找到使用globalsign库连接到mongodb的方法,使用.crt文件。

但是,我成功地使用mongo-driver库实现了这一点。
这里的连接字符串可以采用以下格式:

  1. mongodb://user:password@replicaset-0.com:27017,replicaset-1.com:27017,replicaset-2.com:27017/?ssl=true&amp;tlsCAFile=./ca.crt&amp;tlsCertificateKeyFile=./ca.pem&amp;authSource=admin&amp;replicaSet=replicaset

示例代码:

  1. import (
  2. "context"
  3. "log"
  4. "os"
  5. // "github.com/globalsign/mgo"
  6. mgo "go.mongodb.org/mongo-driver/mongo"
  7. mongoOptions "go.mongodb.org/mongo-driver/mongo/options"
  8. )
  9. func InitMongo() error {
  10. connStr := os.Getenv("MONGODB_CONN_STR")
  11. dbName := os.Getenv("MONGODB_DATABASE")
  12. clientOpts := mongoOptions.Client().ApplyURI(connStr)
  13. if err := clientOpts.Validate(); err != nil {
  14. log.Print("无法解析URL")
  15. log.Fatal(err)
  16. }
  17. client, err := mgo.Connect(context.TODO(), clientOpts)
  18. if err != nil {
  19. log.Print("无法连接到数据库")
  20. log.Fatal(err)
  21. }
  22. if err := client.Ping(context.TODO(), nil); err != nil {
  23. log.Print("数据库ping失败")
  24. log.Fatal(err)
  25. }
  26. //client.Database(dbName)
  27. return nil
  28. }
英文:

After researching a lot, I was not able to find a way to connect to mongodb using .crt file using globalsign library.

However I was successfully able to do this using mongo-driver library.
here connection string can be of format:

  1. mongodb://user:password@replicaset-0.com:27017,replicaset-1.com:27017,replicaset-2.com:27017/?ssl=true&amp;tlsCAFile=./ca.crt&amp;tlsCertificateKeyFile=./ca.pem&amp;authSource=admin&amp;replicaSet=replicaset

Sample code:

  1. import (
  2. &quot;context&quot;
  3. &quot;log&quot;
  4. &quot;os&quot;
  5. // &quot;github.com/globalsign/mgo&quot;
  6. mgo &quot;go.mongodb.org/mongo-driver/mongo&quot;
  7. mongoOptions &quot;go.mongodb.org/mongo-driver/mongo/options&quot;
  8. )
  9. func InitMongo() (error) {
  10. connStr := os.Getenv(&quot;MONGODB_CONN_STR&quot;)
  11. dbName := os.Getenv(&quot;MONGODB_DATABASE&quot;)
  12. clientOpts := mongoOptions.Client().ApplyURI(connStr)
  13. if err := clientOpts.Validate(); err != nil {
  14. log.Print(&quot;unable to parse url&quot;)
  15. log.Fatal(err)
  16. }
  17. client, err := mgo.Connect(context.TODO(), clientOpts)
  18. if err != nil {
  19. log.Print(&quot;unable to connect into database&quot;)
  20. log.Fatal(err)
  21. }
  22. if err := client.Ping(context.TODO(), nil); err != nil {
  23. log.Print(&quot;database ping failed&quot;)
  24. log.Fatal(err)
  25. }
  26. //client.Database(dbName)
  27. return nil
  28. }

huangapple
  • 本文由 发表于 2021年9月23日 19:17:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/69298986.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定