MongoDb连接认证错误(Command failed with error 18)
mongoDb连接时认证异常
最近新起一项目用到了mongodb,然后直接采用 spring-boot-starter-data-mongodb 做依赖直接使用框架的mongodb配置,连接mongo然后开发及测试都没问题,上生产环境后项目也启动正常(项目启动时也能正常连接mongodb)老手新发咔咔的就上线了,本来信心满满,上线后直接就交给用户用了,然后被啪啪打脸了,原因是当点击导出数据从mongo往外导数据的时候报异常,异常如下(很常见的异常吧,但启动能正常连接,查询数据也应该没问题才对):
Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server dds-***************-pub.mongodb.rds.aliyuncs.com:3717. The full response is {"operationTime": {"$timestamp": {"t": 1650956849, "i": 15}}, "ok": 0.0, "errmsg": "Authentication failed.", "code": 18, "codeName": "AuthenticationFailed", "$clusterTime": {"clusterTime": {"$timestamp": {"t": 1650956849, "i": 15}}, "signature": {"hash": {"$binary": {"base64": "bVMy9hNiEO6bzj2IcPay57ku460=", "subType": "00"}}, "keyId": 7042646381365821444}}}
这一看就是启用认证错误嘛,但是看异常信息,明明已经正常读取到配置的用户信息了,而且同样的配置信息在另外一个项目上就可以正常使用,在尝试对用户名密码加双引号等解决方案无效后,就用起了杀手锏“自定义配置”直接自己写mongodb的配置信息(不再采用默认的配置项),经过将老项目的配置信息copy并修改后配置信息如下:
/**
* mongoDb配置项
*
* @return
* @author wjyuse@foxmail.com
* @date 2022-04-26 15:46:50
**/
@Bean
public MongoDatabaseFactory mongoDbFactory() throws Exception {
// Set credentials
MongoCredential credential = MongoCredential.createCredential(userName, database, password.toCharArray());
ServerAddress serverAddress = new ServerAddress(host, port);
// Mongo Client
MongoDriverInformation info = MongoDriverInformation.builder().build();
MongoClientSettings build = MongoClientSettings.builder()
.applyToClusterSettings(builder -> builder.hosts(Collections.singletonList(serverAddress)))
.credential(credential).build();
MongoClient mongoClient = new MongoClientImpl(build, info);
// Mongo DB Factory
return new SimpleMongoClientDatabaseFactory(mongoClient, database);
}
再次放入生产环境后终于OK了。
PS:有时候隐藏在深不见底的地方,哪怕再老的老手也尽量不轻易拍胸脯,否则,有可能会听到啪啪啪的声音!
更多推荐
所有评论(0)