mongodb 6.0 增加密码认证

2022-06-19

在启动认证前,先创建管理员用户,以防切换开启认证后无法登录;admin数据库创建需要的角色权限以方便对数据库进行管理,第一个创建的用户必须在admin库中创建。

MongoServerError: command replSetInitiate requires authentication,如果你已经开启了认证,但是忘了创建任何用户,先注释掉认证需要的配置:
security:
keyFile: /data1/mongodb/config/keyfile
authorization: enabled

1、sed -i 's/fork: true/fork: false/g' /data1/mongodb/config/*.conf;
sed -i 's|\/log|\/logs|g' /data1/mongodb/config/*.conf

2,旧版本是在配置文件中添加auth=true配置,开启安全认证。
config.conf
auth: true

3、在认证启动前,创建管理员切换admin数据库创建需要的角色权限以方便对数据库进行管理,注:第一个创建的用户必须在admin库中创建。

use admin

db.createUser({user:"root",pwd:"password1",
roles:[
{
"role": "root",
"db":"admin"
}
]
})

db.auth("root","password1");
show users;
######################################################
db.createUser({user:"admin",pwd:"password1",
roles:[
{
"role": "dbAdminAnyDatabase",
"db":"admin"
},
{
"role": "userAdminAnyDatabase",
"db":"admin"
},
{
"role": "readWriteAnyDatabase",
"db":"admin"
}
]
})
db.auth("admin","password1");
show users;

4、现在可以开启认证了,是在所有config.conf和shard.conf中增加两项安全认证配置:

#生成key,# 该key的权限必须是600

openssl rand -base64 745 > /data1/mongodb/config/keyfile
chmod 600 /data1/mongodb/config/keyfile

security:
keyFile: /data1/mongodb/config/keyfile
authorization: enabled

在所有mongos.conf添加,去掉authorization: enabled:
security:
keyFile: /data1/mongodb/config/keyfile

db.auth("admin","password1");

5、MongoServerError: Invalid replication write concern. User management write commands may only use w:1 or w:'majority', got: { w: 2, wtimeout: 0, provenance: "customDefault" }

db.adminCommand({ "setDefaultRWConcern": 1, "defaultWriteConcern": { "w": 1 } })

6、创建user,db
use userdb
db.createUser(
{
user:"testuser",
pwd:"password2",
roles:[{role:"dbOwner",db:"userdb"}]
})

db.createCollection('test')

7、mongosh
https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel80-6.0.6.tgz
https://downloads.mongodb.com/compass/mongodb-mongosh-shared-openssl11-1.9.1.x86_64.rpm
rpm -ivh mongodb-mongosh-shared-openssl11-1.9.1.x86_64.rpm

IP=$(hostname -I|awk '{print $1}')
port=7000
mongosh --quiet ${IP}:${port}/admin --authenticationDatabase -u testuser -p password2

分类:Linux数据库 | 标签: |

相关日志

评论被关闭!