Spring Boot 访问开启了安全认证的mongodb

application.yml中的连接配置如下

spring:

data:

mongodb:

uri: mongodb://hospital:Hospital2021@172.16.13.71:47017/iot_platform?authSource=admin

控制台连接信息是正常的:successfully connected to server 但是一调接口就报错:

com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server 172.16.13.71:47017. The full response is {"ok": 0.0, "errmsg": "Authentication failed.", "code": 18, "codeName": "AuthenticationFailed"}

后来发现是authSource的问题:authSource是指认证库,即创建角色或用户时所在的库。

如果登录用户是在admin下创建的,那么 authSource=admin 是没问题的,但如果是在别的库下创建的(例如我上面使用的角色是在库 iot_platform下创建的)那么要使 authSource=iot_platform ,这样才可以通过安全验证!

因此将uri修改为

uri: mongodb://hospital:Hospital2021@172.16.13.71:47017/iot_platform?authSource=iot_platform

问题解决,数据访问成功~

小小记录,算是对自己“拿来主义”的警醒

推荐链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: