`
sillycat
  • 浏览: 2543460 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

MongoDB 2019(3)Security and Auth

 
阅读更多
MongoDB 2019(3)Security and Auth

Started the mongo cluster first
Connect to it
> mongo -host rancher-worker2 -port 27017
> rs.slaveOk();
> db.users.find();

Check DB
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB

Switch to use admin
> use admin
switched to db admin

check if there is any users in DB
> db.system.users.find();
sillycat:PRIMARY>

No users, so I add one user there
https://docs.mongodb.com/manual/tutorial/create-users/
> use admin
switched to db admin

> db.createUser({user: "carl",pwd: "password",roles:[{role: "userAdminAnyDatabase", db:"admin"}]})
Successfully added user: {
"user" : "carl",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}

Verify my auth
> db.auth("carl","password")
1

Exit and change the configuration for mongodb
> vi conf/mongodb.conf
auth = true

Kill the mongo process and start them again one by one
> mongod -f conf/mongodb.conf

In theory, it should be good to go now.
Wrong password will fail
> mongo --host rancher-home --port 27017 -ucarl -padfasdf --authenticationDatabase admin

Good password will be good
> mongo --host rancher-home --port 27017 -ucarl -ppassword --authenticationDatabase admin

> rs.slaveOk();
sillycat:OTHER>

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB

> use admin
Check Users
> db.system.users.find()
{ "_id" : "admin.carl", "userId" : UUID("73415070-d63d-4377-ac3f-a247521a9d43"), "user" : "carl", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "pYlkO1HuxIyKAM9fmnWZvQ==", "storedKey" : "cDocJ/FMaE3+T/KA02kQ+z2tjas=", "serverKey" : "BZe3saf4s7eqzc+Ks6kmvuJRTLw=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "CfET/OxJEo2eRnJufeaVKSmEy+7U89m7XX7NKA==", "storedKey" : "pns2OxgR+zfvJJL07to6PSvhc83R8YfnbrRQXh9xSKo=", "serverKey" : "2DKiqzYZHGszCHsb75VJbjqOrP/LfaEQMkdORPejIPI=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }

Check this
> db.createUser({ user: "mongoadmin" , pwd: "mongoadmin", roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"]})
Successfully added user: {
"user" : "mongoadmin",
"roles" : [
"userAdminAnyDatabase",
"dbAdminAnyDatabase",
"readWriteAnyDatabase"
]
}

Check out these
> db.createUser( { user:"siteUserAdmin",pwd:"password",roles:["userAdminAnyDatabase"]})
Successfully added user: { "user" : "siteUserAdmin", "roles" : [ "userAdminAnyDatabase" ] }

> db.createUser( { user:"siteRootAdmin",pwd:"password", roles:["userAdminAnyDatabase","readWriteAnyDatabase","dbAdminAnyDatabase","clusterAdmin"]});
Successfully added user: {
"user" : "siteRootAdmin",
"roles" : [
"userAdminAnyDatabase",
"readWriteAnyDatabase",
"dbAdminAnyDatabase",
"clusterAdmin"
]
}

It is said the MongoDB Replica set needs both user account and keyfile. Keyfile seems for authentication between servers in the replica set, not for login in.
All the configurations are listed here
https://docs.mongodb.com/manual/reference/configuration-options/

Try the settings as follow:
storage:
    dbPath: "/data/db/mongodb"
    directoryPerDB: true
    journal:
        enabled: true
systemLog:
    destination: file
    path: "/var/log/mongodb/mongod.log"
    logAppend: true
    timeStampFormat: iso8601-utc
replication:
    oplogSizeMB: 10240
    replSetName: "sillycat"
processManagement:
    fork: true
net:
    bindIp: 0.0.0.0
    port: 27017
security:
    keyFile: "/opt/mongodb/keyfile.key"
    authorization: "enabled"

Check version
> mongod -version
db version v4.2.1
git version: edf6d45851c0b9ee15548f0f847df141764a317e
OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013
allocator: tcmalloc
modules: none
build environment:
    distmod: rhel70
    distarch: x86_64
    target_arch: x86_64

Create the keyfile, we usually generate the keyfile on one server, copy that to other servers.
> openssl rand -base64 90 -out ./keyfile.key
Change the permission
> chmod 600 ./keyfile.key
Copy the file to other machines, make sure all 3 nodes having the same keyfile

> sudo rm -fr /data/db/mongodb/*
Facing some failure, because of the previous database data directory is keeping some old configurations. Clear that directories, and restart, it works fine.
We can always check the logging here
> tail -f /var/log/mongodb/mongod.log

> mongod -f conf/mongodb.conf
The final configurations are as follow:
> cat conf/mongodb.conf
storage:
    dbPath: /data/db/mongodb
    directoryPerDB: true
    journal:
        enabled: true
systemLog:
    destination: file
    path: /var/log/mongodb/mongod.log
    logAppend: true
replication:
    oplogSizeMB: 10240
    replSetName: sillycat
processManagement:
    fork: true
net:
    bindIp: 0.0.0.0
    port: 27017
security:
    keyFile: /opt/mongodb/keyfile.key
    authorization: enabled

Disable the security—>authorization and security—>keyFile ,restart the services again
Connect to the master server again
> mongo --host rancher-home --port 27017
> rs.status()
{
"operationTime" : Timestamp(0, 0),
"ok" : 0,
"errmsg" : "no replset config has been received",
"code" : 94,
"codeName" : "NotYetInitialized",
"$clusterTime" : {
"clusterTime" : Timestamp(0, 0),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}
> rs.initiate()
sillycat:SECONDARY> rs.conf()
sillycat:PRIMARY> rs.add("rancher-worker1:27017")
sillycat:PRIMARY> rs.add("rancher-worker2:27017")

That will recreate the master and 2 replicas.
Create some important user
User root as root role
> db.createUser({user:"root",pwd:"123456",roles:[{role:"root",db:"admin"}] });

sillycat:PRIMARY> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

sillycat:PRIMARY> use admin
switched to db admin

User admin is admin of any database
> db.createUser({user:"admin", pwd:"admin", roles:[{role: "userAdminAnyDatabase", db:"admin" }]})

It works
> sillycat:PRIMARY> db.auth("admin","admin")
1

Create a new database
> sillycat:PRIMARY> use testdb1
switched to db testdb1

Create db owner
> sillycat:PRIMARY> db.createUser({user:"carl",pwd:"123456",roles:[{role:"dbOwner",db:"testdb1"}] })
It works well
sillycat:PRIMARY> db.auth("carl","123456")
1

Shutdown all the services
> mongo --host rancher-home --port 27017
> mongo --host rancher-worker1 --port 27017
> mongo --host rancher-worker2 --port 27017

> sillycat:PRIMARY> use admin
sillycat:PRIMARY> db.shutdownServer()

Need to use local to connect to shutdown the service
> mongo --host localhost --port 27017

Enable all the configurations
security:
    keyFile: /opt/mongodb/keyfile.key
    authorization: enabled

Start the service again
> mongod -f conf/mongodb.conf

Check admin first
> mongo --host rancher-home --port 27017 -uadmin -padmin --authenticationDatabase admin

Check other db
> mongo --host rancher-home --port 27017 -ucarl -p123456 --authenticationDatabase testdb1
sillycat:PRIMARY> use testdb1
sillycat:PRIMARY> db.users.insert({name:"Carl", age:31})
sillycat:PRIMARY> db.users.find();
{ "_id" : ObjectId("5dcf23e43a8ac5e8fb8bd004"), "name" : "Carl", "age" : 31 }

On slave
> mongo --host rancher-worker1 --port 27017 -ucarl -p123456 --authenticationDatabase testdb1
sillycat:SECONDARY> rs.slaveOk();

sillycat:SECONDARY> db.users.find();
{ "_id" : ObjectId("5dcf23e43a8ac5e8fb8bd004"), "name" : "Carl", "age" : 31 }

Some other command
sillycat:SECONDARY> use testdb1
switched to db testdb1

sillycat:SECONDARY> show dbs
testdb1  0.000GB

sillycat:SECONDARY> show collections
users

Check current db
> sillycat:SECONDARY> db
test


References:
https://docs.mongodb.com/manual/core/authentication/
https://stackoverflow.com/questions/20539376/a-mongodb-useradminanydatabase-user-cannot-admin-users-in-any-database-why
http://www.dba86.com/docs/mongo/2.4/tutorial/deploy-replica-set-with-auth.html
https://stackoverflow.com/questions/38524150/mongodb-replica-set-with-simple-password-authentication
https://docs.mongodb.com/manual/tutorial/deploy-replica-set-with-keyfile-access-control/
https://github.com/johnnian/Blog/issues/8
https://dba.stackexchange.com/questions/82591/sample-yaml-configuration-files-for-mongodb
https://nutao.github.io/2017/07/27/Mongodb-%E9%9B%86%E7%BE%A4%E8%AE%A4%E8%AF%81%EF%BC%88KeyFile%EF%BC%89/
https://www.cnblogs.com/cswuyg/p/5869256.html
分享到:
评论

相关推荐

    Linux下MongoDB安装包

    然后,修改`/etc/mongod.conf`配置文件,添加`auth`参数并重启MongoDB: ```bash security: authorization: enabled ``` 重启MongoDB服务并用新创建的用户登录: ```bash sudo service mongod restart ...

    mongodb-linux-x86_64-rhel70-4.4.13安装包和conf配置文件

    5. **权限与安全**:为了保护数据库,你可以启用身份验证(`auth`),并配置`security.keyFile`来实现基于密钥的认证。 示例配置文件内容可能如下: ``` systemLog: destination: file path: /var/log/mongodb/...

    Java开发之spring security实现基于MongoDB的认证功能

    本文将详细介绍如何在Spring Security中集成MongoDB实现认证功能。 首先,我们需要理解Spring Security的认证流程。Spring Security通过`UserDetailsService`接口来获取用户信息,这个接口的主要方法是`...

    毕业设计&课设_集成spring-boot-security-jwt-auth-mongodb的项目.zip

    该资源内项目源码是个人的课程设计、毕业...3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。

    mongodb未授权漏洞加固.pdf

    3. **配置防火墙规则**:限制MongoDB监听端口仅允许特定IP或范围内的IP访问。例如,只允许本地访问: ```bash netstat -tuln | grep 27017 iptables -A INPUT -p tcp --dport 27017 -j DROP ``` 4. **禁用远程...

    Mongodb 配置

    3. **启动MongoDB服务** 在Windows上,可以使用命令行工具(如cmd或PowerShell)进入MongoDB的`bin`目录,然后运行`mongod.exe --config <配置文件路径>`启动服务。如果需要后台运行,可以加上`--service`参数。 4...

    Spring boot + Spring Security 简单配置实例

    在本文中,我们将深入探讨如何使用Spring Boot与Spring Security进行简单的安全配置,同时结合MongoDB作为数据存储。Spring Boot以其简化Spring应用开发的特性而受到广泛欢迎,而Spring Security则是Java安全领域的...

    mac 版 mongodb

    在 `mongod.conf` 文件中添加 `security` 和 `auth` 部分: ``` security: authorization: enabled net: bindIp: 127.0.0.1,::1 # 只允许本地连接 ``` 然后,首次启动时,你需要初始化一个管理员用户: 1. 运行...

    Mongodb4.x介绍以及Mongodb账户权限配置1

    2. 修改 MongoDB 配置文件:在 `mongod.cfg` 文件中启用授权,将 `security.authorization` 设置为 `enabled`。 3. 重启 MongoDB 服务:更新配置后,需要重启服务以应用更改。 4. 使用超级管理员账户连接数据库:...

    Practical Node.js: Building Real-World Scalable Web Apps, 2nd Edition

    Chapter 6: Security and Auth in Node.js Chapter 7: Boosting Node.js and MongoDB with Mongoose Chapter 8: Building Node.js REST API Servers with Express.js and Hapi Chapter 9: Real-Time Apps with ...

    MongoDB复制集搭建

    db.getSiblingDB("admin").auth("root", "root@want") ``` 或者,我们可以使用以下命令进行身份验证: ``` mongo -u "root" -p --authenticationDatabase "admin" ``` 8. 创建 Cluster 管理员用户(可选) 如果我们...

    mongodb 4.4.13安装包与配置文件

    - `security`: 这里可以配置认证和授权选项,如启用权限控制 (`auth = true`) 和设置用户认证机制。 - `replication`: 如果需要配置复制集,可以在这里定义成员。 - `sharding`: 对于分片集群,这里可以设置分片配置...

    sso-auth:具有Spring OAuth2和MongoDB的单一登录身份验证服务器

    我解释了如何选择OAuth 2.0和MongoDB来构建可在微服务体系结构中使用的Single Sign On Auth服务器。 1.第一步。 运行sso-auth-client应用程序。 并尝试访问 。 不传递任何标题就返回此 2.第二步。 运行sso-auth-...

    MongoDB 3.0+安全权限访问控制详解

    要开启访问控制,需要编辑MongoDB配置文件(如`/etc/mongod.conf`),将`security.authorization`设置为`enabled`。确保键值之间有空格,然后重启服务。 5. **用户管理员身份验证** 连接到MongoDB时,需要使用`-u...

    MongoDB系列教程(四):设置用户访问权限

    3. 在右侧键值列表中找到`ImagePath`,并在其值末尾添加空格后加上`-auth`,确保重启MongoDB服务以使更改生效。 一旦完成上述步骤,MongoDB将要求用户提供凭证才能访问。尝试不提供凭证时,系统会拒绝访问并抛出...

    MongoDB开启权限认证的方法步骤详解

    1. **修改MongoDB配置**:编辑MongoDB配置文件(通常是`/etc/mongod.conf`),在`security`部分添加`authorization: enabled`,确保`--auth`参数生效。 2. **重新启动MongoDB**:使用`sudo service mongod restart`...

    Mongodb 3.2.9开启用户权限认证问题的步骤详解

    3. **重启 MongoDB 服务**:配置 MongoDB 服务器以启用身份验证。在 MongoDB 的配置文件(如 `/etc/mongod.conf`)中添加 `auth` 参数: ```ini security: authorization: enabled ``` 4. **重新启动服务**:...

    auth-server:验证服务器

    3. **Java Security Framework**:auth-server基于Java平台,利用Java的安全框架来实现复杂的认证和授权功能。Java提供了强大的安全API,如JASPI(Java Authentication and Authorization Service)和JAAS(Java ...

Global site tag (gtag.js) - Google Analytics