更新於 2024/08/29閱讀時間約 3 分鐘

MongoDB authentication and replication feat. pymongo

Authentication

It’s dangerous to deploy a DB server without authentication. People could just access your DB by knowing where you host your DB. At least we should create a username and password to do the basic authentication.

create root user
I would like to take a quick exercise about authentication, so let’s cut the shit about different kinds of users and permission.
In the mongo shell, create a root user to handle everything as follows.
$ use admin
$ db.createUser( { user: “superuser”, pwd: “yourpwd”, roles: [ { role: “root”, db: “admin” } ] } )

mongod.cfg
Enable the authorization in the MongoDB config as follows.

connection
Let’s use pymongo as the driver in python back-end for example.
'mongodb://'+db_root_user+':'+db_root_password+'@'+db_host+':'+str(db_port)+'?authSource=admin' would pass the username and password by url.

Replication

I wrote an article about MongoDB replication before. Please check it in this url: https://medium.com/@xdxxxx4713/mongodb-replication-45ac3e6d6b30

connect DB in the back-end
To use both authentication and replication techniques, we would use pymongo as follows.
Set the db_host as the combination of the hosts of primary servers and secondary servers. Then we can use the both authentication and replication technique right now.

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.