Note:
- MongoDB
v4.4.3
- 认证默认未开启的情况下,执行以下步骤
建立超级用户
用于管理其他用户
- 创建超级用户
> use admin
> db.CreateUser(
{
user: "admin",
pwd: passwordPrompt(),
roles: [
{role: "userAdminAnyDatabase", db: "admin"},
"readWriteAnyDatabase" // 可以不设置此项,只是为了开发方便
]
}
userAdminAnyDatabase
: 是任一数据库的 userAdmin(角色管理,不涉及数据权限)Provides the same access to user administration operations as userAdmin on all databases except local and config.
readWriteAnyDatabase
: 可以读写任一数据库Provides the same privileges as readWrite on all databases except local and config.
- 结果查看:
show users
创建目标用户
> use medley // 切换数据库 (此数据库既是 database,后续也作为 user 认证的 authentication-database
> db.CreateUser(
{
user: "medley",
pwd: passwordPrompt(),
roles: [
{role: "dbOwner", db: "medley"}
]
}
dbOwner
: can perform any administrative action on the database.组合
readWrite
,dbAdmin
anduserAdmin
三者
- 结果查看:
show users
开启认证
- 退出 mongo shell
> exit
- 关闭 mongod 服务
# linux
ps -aux | grep mongod
kill -9 xxx
# windows
net stop MongoDB // 之前开启的对应服务
- 修改 mongod.yml
$ vim /path/to/mongod.yml
# 添加
security:
authorization: enabled
亦可:If you start the
mongod
from the command line, add the--auth
command line option:mongod --auth --port 27017 --dbpath /var/lib/mongodb
- 重启 mongod 服务
# linux
mongod --config /path/to/mongod.yml --fork // 后台运行
# windows
net start MongoDB
连接
- mongo shell 方式
$ mongo medley -u medley -p <pwd> --authenticationDatabase medley
或者
$ mongo "mongodb://medley:<pwd>@localhost:27017/medley?authSource=medley"
如果 database 与 认证库一致,则可以省略
--authenticationDatabase args
或者authSource=xx
- SpringBoot 配置
application.yml
spring:
data:
mongodb:
uri: mongodb://medley:<pwd>@127.0.0.1:27017/medley?authSource=medley
或者
spring:
data:
mongodb:
username: medley
password: <pwd>
host: 127.0.0.1
port: 27017
database: medley
authentication-database: medley
如果
database
和authentication-database
一致,则后者可以省略
疑惑
通过 db.createCollection("col")
创建的 collection,无法正常插入/删除,会提示 uncaught exception: TypeError: db.hello.insert is not a function :
类似的错误
db.col.insert({“a”: “b”})
db.col.find()
db.col.drop()
db.col.help()
- 如果要使用上述方法,必须如下: db.getCollection(“hello”).func()
- 但通过 db.col.insert({}) 创建的 collection,可以正常执行各种方法
db.col.help() 查看
Reference