连接信息:
//MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码MongoCredentialcredential= MongoCredential.createScramSha1Credential("root","source","123456".toCharArray());List credentials= newArrayList();credentials.add(credential);
报错信息:
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" }
#首先排除了【SCRAM-SHA-1】错误
经过查阅资料发现是使用了错误的授权账号
MongoDB中每个数据库之间是相互独立的,都有独立的权限,正确的做法是使用root账号在【将要操作的数据库】中创建一个【子账号】,在用这个子账号连接mongo
例如:
>use admin
switched to db admin
>db.auth("root","123456")
1
>show dbs
admin
local
testDB
>use testDB
switched to db testDB
>db.createUser(
{
user:"usertest",
pwd:"123456",
roles:[{role:"dbOwner",db:"testBD"}]
}
)
Successfully added user: {
"user" : "usertest",
"roles" : [
{
"role" : "dbOwner",
"db" : "testDB"
}
]
}
最后使用【usertest】来替换java代码中的账号【root】