We will conclude this chapter by informing you about database security. So far, we have started and used MongoDB without any authentication process. Actually, starting mongod without any additional option exposes the database to any user who is aware of the process.
We will show how to provide secure access by means of the mongo shell. So, launch the mongo shell and connect to the admin database, which holds information about the users:
use admin
Now, let's use the createUser function to add a user named administrator with the password mypassword and grant unlimited privileges (the role root):
db.createUser(
{
user: "administrator",
pwd: "mypassword",
roles: [ "root" ]
}
)
Now, shut down the server by using the following command:
db.shutdownServer()
We will restart the database using the –-auth option, which forces user authentication:
mongod --dbpath "C:\mongodb-win32-x86_64-3.0.3\data" --auth
Now, the database is started in secure mode. You can connect from the mongo shell in two different ways. The first one should be used with caution on Linux/Unix systems, as it exposes the user/password in the process list:
mongo -u administrator -p mypassword --authenticationDatabase admin
As an alternative, you can start the mongo shell and authenticate it at the beginning of the session (you need to select the admin database at first as the authentication keys are stored on the admin DB):
use admin
db.auth('admin','mypassword')
No hay comentarios:
Publicar un comentario