In one of my projects, I am using python to parse information and store it in mongoDB. I wanted to run and test everything locally on my machine. I wanted to set it up using the following guidelines:
- One user that has read/write access to one DB in mongo.
- One user that has read-only access to one DB in mongo (to serve web queries).
- Neither of the previous users have ‘admin’ access.
Here is a tutorial on how to go about achieving that setup.
Note: I was using a Mac in this setup (10.12, Sierra) in my setup.
Creating a Super User
When creating users in mongoDB, the first thing to do (after installing mongodb of course) is to start the server up. After starting it up and logging into the CLI, you should set up a ‘super user’. You’ll use this user to log into your mongo instance after you have started the instance with ‘auth’ enabled.
Luckily mongo (3.0+) has a superuser role already baked into it. This makes it very easy to create an ‘admin’ user.
After creating a super user, you’ll be able to start your mongo instance in a mode that requires authentication.
Creating Other Users
When your mongo instance starts in auth mode, you’ll have to log into it using the user you created in the previous step. Assuming that your mongo instance is running locally, you can log into it using your super user to create other, more specific users.
As I said in my requirements, I wanted to set up two users: both users were specific to a database where one had read/write access and the other had only read access.
After you log into the mongo instance with your admin user, make sure you’re using the db in which you want to define the user. I didn’t do this the first time and I was very confused as to why I couldn’t log in using my newly-created user.
Cool, we’re on the ‘datadb’ database that is set up to store the data. Now to create the users.
The database used to set up users (in this case, ‘datadb’) will have to be part of the command used to log into the mongo CLI.
Authenticating Users in PyMongo
Now it’s time to use the read/write user created in the previous steps in a python script. This python script uses PyMongo to interact with my local mongo instance. The following code segment demonstrates how to authenticate the user using the setup in the previous sections of this post.
from pymongo import MongoClient def store_info(info): client = MongoClient() db = client.datadb db.authenticate('writer', 'writer1', source='datadb') # The rest of the code...
And there you have it! The users are set up and you’re able to authenticate your mongo access via a python script.