【发布时间】:2020-08-17 10:46:56
【问题描述】:
我正在尝试使用 go 语言通过本机 MongoDB 驱动程序连接 MongoDB (ref)。
这是我的快照代码。
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
account = "rootAdmin"
password = "12345678"
iP = "127.0.0.1"
port = 27017
tlsCertificateKeyFile = "D:/cert/wa.pem"
)
type mongoStuff struct {
ctx context.Context
client *mongo.Client
cancel context.CancelFunc
}
func connectToMongoDB() *mongoStuff {
uri := fmt.Sprintf("mongodb://%v:%v@%v:%v/?authSource=admin&tlsCertificateKeyFile=%v&tls=true",
account,
password,
iP,
port,
tlsCertificateKeyFile)
credential := options.Credential{
AuthMechanism: "MONGODB-X509",
Username: account,
Password: password,
}
log.Println(uri)
clientOpts := options.Client().ApplyURI(uri).SetAuth(credential)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
client, err := mongo.Connect(ctx, clientOpts)
if err != nil {
log.Println("Dead connect")
log.Fatal(err)
}
return &mongoStuff{ctx, client, cancel}
}
func disconnectMongoDB(mongodb *mongoStuff) {
cancel := mongodb.cancel
client := mongodb.client
ctx := mongodb.ctx
defer cancel()
defer func() {
if err := client.Disconnect(ctx); err != nil {
log.Println("Dead disconnect")
panic(err)
}
}()
}
func insertExamples(mongodb *mongoStuff) {
ctx := mongodb.ctx
var db *mongo.Database = mongodb.client.Database("documentation_examples")
coll := db.Collection("inventory_insert")
err := coll.Drop(ctx)
if err != nil {
log.Println("Dead drop")
log.Fatal(err)
}
{
result, err := coll.InsertOne(
ctx,
bson.D{
{"item", "canvas"},
{"qty", 100},
{"tags", bson.A{"cotton"}},
{
"size", bson.D{
{"h", 28},
{"w", 35.5},
{"uom", "cm"},
}},
})
if err != nil {
log.Println("Dead insertone")
log.Fatal(err)
}
log.Printf("insertone success. id=%v", result.InsertedID)
}
}
func main() {
mongodb := connectToMongoDB()
defer disconnectMongoDB(mongodb)
insertExamples(mongodb)
}
每当我运行代码时,它都会出现以下错误。
连接握手期间发生连接()错误:身份验证错误:往返错误:(AuthenticationFailed)未提供用户名
我不知道发生了什么。
【问题讨论】:
-
身份验证机制提到 X.509 对我来说看起来很奇怪:这个标准定义了公钥证书的格式(那些在 TLS 和其他地方使用的)。
-
是的,我想通过 TLS 连接到 Mongo。我的代码有问题吗?
-
您是否正确配置 MongoDB 以使用 cert 和 user:pass?
-
似乎运行良好。我可以通过 MongoDB Compass 使用认证文件(*.pem 文件)连接到服务器