springboot 和 mongdb連接問題 Exception in thread "main" com.mongodb.MongoSecurityException:


1 Exception in thread "main" com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='user', source='userdb', password=<hidden>, mechanismProperties={}}
2 Caused by: com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server 你的IP:你的端口. The full response is { "ok" : 0.0, "errmsg" : "Authentication failed.", "code" : 18, "codeName" : "AuthenticationFailed" }

出現以上springboot 2.x連接 mongdb 3.x的情況。

直面意思,就是指認證失敗。

情況有4種,

1.你的認證方式有問題

2.認證信息有誤(用戶名密碼等配錯了)

3.mongodb數據庫問題

4.springboot yml配置錯誤


1.你的認證方式有問題

SCRAM-SHA-1:就是mongodb 3.x之后默認的認證方式,springboot 2.x之后也是可以選擇這種方式。
注意:mechanism=SCRAM-SHA-1。如果你不是這種方式,你就要升級你的springboot版本,或者去修改你的mongdb數據庫的認證方式/降低mongodb版本。

你用純javamongodb-driver包測試時,可見com.mongodb.MongoCredential 類下選取的認證方式來源於如下類。
public enum AuthenticationMechanism {
    GSSAPI("GSSAPI"),
    PLAIN("PLAIN"),
    MONGODB_X509("MONGODB-X509"),
    /** @deprecated */
    @Deprecated
    MONGODB_CR("MONGODB-CR"),
    SCRAM_SHA_1("SCRAM-SHA-1"),
    SCRAM_SHA_256("SCRAM-SHA-256");

    private static final Map<String, AuthenticationMechanism> AUTH_MAP = new HashMap();
    private final String mechanismName;

    private AuthenticationMechanism(String mechanismName) {
        this.mechanismName = mechanismName;
    }

2.認證信息有誤(用戶名密碼等配錯了)

  如果你手動,改錯 數據庫名或者用戶名密碼,你會發現也是會報這個錯誤。

3.mongdb數據庫問題

  用戶權限問題。正確的用戶創建如下:

use mydb
#沒有數據庫會自動創建

#在此數據庫下創建用戶
db.createUser(
  {
    user: "user",
    pwd: "123456",
    roles: [ { role: "readWrite", db: "mydb" } ]
  }
)

#重新進入,開啟auth參數,認證通過后才能訪問數據庫
./mongod -f mongdb.conf --auth

db.auth("user","123456")  認證通過后可以操作數據庫。

 4.springboot yml配置錯誤

spring:
  application:
      name: test
  data:
    mongodb:
      host: 你的Ip
      username: user
      password: 123456
      database: user
      port: 1234

#如果你是上面這種配置方式,那么恭喜你。他根本不會成功
#正確配置是如下這種方式
     uri: mongodb://user:123456@你的Ip:1234/user

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM