1. 程式人生 > >使用java連線Mongodb時報錯code:18codeName:AuthenticationFailed時的解決方法

使用java連線Mongodb時報錯code:18codeName:AuthenticationFailed時的解決方法

連線資訊:

//MongoCredential.createScramSha1Credential()三個引數分別為 使用者名稱 資料庫名稱 密碼
MongoCredential credential = MongoCredential.createScramSha1Credential("root", "source", "123456".toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
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】