SpringBoot连接Mongodb报错:Authentication failed

文章讲述了在使用SpringBoot访问开启了安全认证的MongoDB时遇到的授权问题。错误源于authSource配置不正确,需指向用户创建时所在的数据库。通过修正uri中的authSource参数,从admin更改为iott_platform,成功解决了认证失败的问题,实现了数据的正常访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
successfully connected to server
但是一调接口就报错:
AuthenticationFailed

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值