MongoDB(二):访问与用户管理


在这里插入图片描述

1、概述

大家好,我是欧阳方超,可以关注我的公众号“欧阳方超”,后续内容将在公众号首发。
MongoDB默认只允许本机访问,且不需要用户名密码,如果要实现远程通过用户名密码进行连接,则需要进行相关的设置,本篇将介绍这些内容。

2、设置远程访问

如果遇到无法远程访问mongodb服务的情况,需要在mongod.conf配置文件中添加以下内容:

net:
  port: 27017
  bindIp: ::,0.0.0.0

以上配置表示允许所有IPv4和IPv6地址访问mongodb。

3、开启认证

默认情况下mongodb未开启认证,这意味着所有人都能够连接mongodb服务,这是不允许的,开启mongodb的认证大致分为两个步骤,第一步创建用户,第二步是在mongodb配置文件中开启认证。

3.1、创建用户

3.1.1、创建管理员账号

创建管理员账号需要在admin库中操作,

use admin
switched to db admin

然后执行show users命令,表示要请求显示该数据库中的所有用户,

show users
[]

可以看到admin库中没有任何用户。

创建管理员账号
进入admin库,创建管理员账号。

db.createUser({user:"mongoadmin",pwd:"p@ss",roles:["root"]})
{ ok: 1 }

查看用户:

show users
[
  {
    _id: 'admin.mongoadmin',
    userId: UUID('ac395eca-8112-4aeb-a87d-0a940c36f1ea'),
    user: 'mongoadmin',
    db: 'admin',
    roles: [
      {
        role: 'root',
        db: 'admin'
      }
    ],
    mechanisms: [
      'SCRAM-SHA-1',
      'SCRAM-SHA-256'
    ]
  }
]

此时连接mongodb服务依然不需要认证,需要在mongodb的配置文件中开启认证:

security:
  authorization: enabled

要使认证生效的话,需要重启mongodb。

使用auth()对刚刚创建的管理员账号进行身份验证:

admin> db.auth("mongoadmin", "p@ss")
{ ok: 1 }
admin>

至此管理员mongoadmin已成功创建。

3.1.2、通过命令行连接mongodb

确认连接时是否需要密码,在连接mongodb时先不输入用户信息:

[root@hadoop104 bin]# ./mongosh
Current Mongosh Log ID: 65fcf6cd062356915cebf4c2
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.0.2
Using MongoDB:          7.0.2
Using Mongosh:          2.0.2

For mongosh info see: https://docs.mongodb.com/mongodb-shell/


Deprecation warnings:
  - Using mongosh on the current operating system is deprecated, and support may be removed in a future release.
See https://www.mongodb.com/docs/mongodb-shell/install/#supported-operating-systems for documentation on supported platforms.
test>

可以进入数据库,但是查询里面的集合时就报错了,提示说需要认证:

test> show collections
MongoServerError: Command listCollections requires authentication
test>

使用用户名密码连接:

[root@hadoop104 bin]# ./mongosh admin -u mongoadmin -p p@ss
Current Mongosh Log ID: 65fcf7d1621e0b0e1f3bcd51
Connecting to:          mongodb://<credentials>@127.0.0.1:27017/admin?directConn                                                                            ection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.0.2
Using MongoDB:          7.0.2
Using Mongosh:          2.0.2

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

------
   The server generated these startup warnings when booting
   2024-03-22T11:10:47.143+08:00: You are running this process as the root user,                                                                             which is not recommended
   2024-03-22T11:10:47.145+08:00: You are running on a NUMA machine. We suggest                                                                             launching mongod like this to avoid performance problems: numactl --interleave=a                                                                            ll mongod [other options]
   2024-03-22T11:10:47.145+08:00: /sys/kernel/mm/transparent_hugepage/enabled is                                                                             'always'. We suggest setting it to 'never'
   2024-03-22T11:10:47.145+08:00: /sys/kernel/mm/transparent_hugepage/defrag is                                                                             'always'. We suggest setting it to 'never'
   2024-03-22T11:10:47.145+08:00: vm.max_map_count is too low
------


Deprecation warnings:
  - Using mongosh on the current operating system is deprecated, and support may                                                                             be removed in a future release.
See https://www.mongodb.com/docs/mongodb-shell/install/#supported-operating-syst                                                                            ems for documentation on supported platforms.
admin> show collections
system.users
system.version

可以看到,可以连接mongodb,并且由于此时创建的用户为管理员用户,可以操作任何库中的集合,但是登录时只能登录到用户所在的数据库(创建用户时所在的数据库)。

3.1.3、创建普通用户

创建用户时需要注意当前在哪个数据库,因为创建的用户只能直接连接到创建该用户时所在的数据库。

use test
switched to db test
test>db.createUser({user:"commonuser1",pwd:"p@ss",roles:[{role:"readWrite",db:"testDB1"},{role:"read",db:"testDB2"}]})

上面的命令创建了commonuser1这个普通用户,授予他对testDB1库的读写权限,对testDB2库的只读权限。
下面的操作展示了commonuser1用户对testDB1库可读、可写:

testDB1> db.col1.insert({name:"apple"})
DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.
{
  acknowledged: true,
  insertedIds: { '0': ObjectId("65fd252a8438414ce93ef50f") }
}
testDB1> db.col1.find()
[ { _id: ObjectId("65fd252a8438414ce93ef50f"), name: 'apple' } ]
testDB1>

下面的命令展示了commonuser1用户对testDB2库有可读权限,但是没有可写权限:

testDB2> db.col2.find()
[ { _id: ObjectId("65fd28ff532f0535d9b3f909"), name: 'pear' } ]
testDB2>

testDB2> db.col2.updateOne({}, {$set:{name:"pear1"}})
MongoServerError: not authorized on testDB2 to execute command { update: "col2", updates: [ { q: {}, u: { $set: { name: "pear1" } } } ], ordered: true, lsid: { id: UUID("360b5646-30b7-4532-9e1a-06a1d4422675") }, $db: "testDB2" }
testDB2>

3.2、查询用户信息

下面的命令将输出用户的详细信息,包括用户名、角色、所在数据库等。
查询当前数据库中所有的用户信息:

admin> show users
[
  {
    _id: 'admin.mongoadmin',
    userId: new UUID("ac395eca-8112-4aeb-a87d-0a940c36f1ea"),
    user: 'mongoadmin',
    db: 'admin',
    roles: [ { role: 'root', db: 'admin' } ],
    mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
  }
]

查询指定用户的信息:

admin> db.getUser("mongoadmin")
{
  _id: 'admin.mongoadmin',
  userId: new UUID("ac395eca-8112-4aeb-a87d-0a940c36f1ea"),
  user: 'mongoadmin',
  db: 'admin',
  roles: [ { role: 'root', db: 'admin' } ],
  mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
}

3.3、修改用户密码

admin> db.updateUser("mongoadmin", {pwd:"mima1"})
{ ok: 1 }

修改密码后可以使用auth()进行验证:

admin> db.auth("mongoadmin", "mima1")
{ ok: 1 }

3.3、删除用户

admin> db.dropUser("mongoadmin")
{ ok: 1 }

4、总结

MongoDB默认没有管理员账号,需要在admin库中添加,然后在配置文件中开启权限认证后,给MongoDB设置的账号才可用;添加普通账号在非admin库进行即可;用户只能直接连接到创建该用户时所在的数据库(包括管理员),然后使用use切换到其他库,至于能否操作数据视有无权限而定。
我是欧阳方超,把事情做好了自然就有兴趣了,如果你喜欢我的文章,欢迎点赞、转发、评论加关注。我们下次见。

  • 37
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值