使用java连接Mongodb时报错:Command failed with error 18 (AuthenticationFailed): ‘Authentication failed.’

报错信息:

Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server XXXXXXX:27017. The full response is { "ok" : 0.0, "errmsg" : "Authentication failed.", "code" : 18, "codeName" : "AuthenticationFailed" }

经过查阅资料发现是使用了错误的授权账号

MongoDB中每个数据库之间是相互独立的,都有独立的权限,正确的做法是使用root账号在【将要操作的数据库】中创建一个【子账号】,在用这个子账号连接mongo:

>use admin

switched to db admin

>db.auth("root","123456")

1

>show dbs

admin   0.000GB
config  0.000GB
good    0.000GB
local   0.000GB
test    0.000GB

>use good

switched to db good

> db.createUser({user:"daniel",pwd:"123456",roles:[{role:"dbOwner",db:"good"}]})
Successfully added user: {
        "user" : "daniel",
        "roles" : [
                {
                        "role" : "dbOwner",
                        "db" : "good"
                }
        ]
}

最后在java代码中的代入账号、密码等。

发布了52 篇原创文章 · 获赞 58 · 访问量 59万+

猜你喜欢

转载自blog.csdn.net/qq_35893120/article/details/100142232