springboot 连接mongodb认证失败解决
报错如下:org.springframework.dao.DataAccessResourceFailureException: Timed out after 30000 ms while waiting for a server that matches WritableServerSelector. Client view of cluster state is {type=UNKNOWN, servers=[{address=192.168.140.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName=‘zcb’, source=‘p2p’, password=, mechanismProperties={}}}, caused by {com.mongodb.MongoCommandException: Command failed with error 18: ‘Authentication failed.’ on server 192.168.140.1:27017. The full response is { “ok” : 0.0, “errmsg” : “Authentication failed.”, “code” : 18, “codeName” : “AuthenticationFailed” }}}]; nested exception is com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches WritableServerSelector. Client view of cluster state is {type=UNKNOWN, servers=[{address=192.168.140.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName=‘zcb’, source=‘p2p’, password=, mechanismProperties={}}}, caused by {com.mongodb.MongoCommandException: Command failed with error 18: ‘Authentication failed.’ on server 192.168.140.1:27017. The full response is { “ok” : 0.0, “errmsg” : “Authentication failed.”, “code” : 18, “codeName” : “AuthenticationFailed” }}}]
解决:
application.yml配置:
spring:
data:
mongodb:
uri: mongodb://admin:123456@localhost:27017/?authSource=admin
database: users
说明:
authSource=admin 为认证数据库(用户具有所有权限可任意指定database,不存在会自动创建)
authMechanism=SCRAM-SHA-1 为认证方式(一般默认是MONGODB-CR)