DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Databases
  4. MongoDB Authentication and Roles: Creating Your First Personalized Role

MongoDB Authentication and Roles: Creating Your First Personalized Role

In this blog post, we’ll walk through the native MongoDB authentication and roles, and learn how to create personalized roles.

Adamo Tonete user avatar by
Adamo Tonete
·
May. 24, 17 · Tutorial
Like (3)
Save
Tweet
Share
7.74K Views

Join the DZone community and get the full member experience.

Join For Free

MongoDB features a few authentication methods and built-in roles that offer great control of both who is connecting to the database and what they are allowed to do. However, some companies have their own security policies that are often not covered by default roles. This blog post explains not only how to create personalized roles, but also how to grant minimum access to a user.

Authentication Methods

SCRAM-SHA-1 and MONGODB-CR are challenge-response protocols. All the users and passwords are saved encrypted in the MongoDB instance. Challenge-response authentication methods are widely used on the internet in several server-client software. These authentication methods do not send passwords as plain text to the server when the client is starting an authentication. Each new session has a different hash/code, which stops people from getting the password when sniffing the network.

The MONGODB-CR method was deprecated in version 3.0.

The x.509 authentication is an internal authentication that allows instances and clients to communicate to each other. All certificates are signed by the same Certificate Authority and must be valid. All the network traffic is encrypted by a given key, and it is only possible to read data with a valid certificate signed by such key.

MongoDB also offers external authentications such as LDAP and Kerberos. When using LDAP, users can log into MongoDB using their centralized passwords. The LDAP application is commonly used to manage users and passwords in wide networks. Kerberos is a service that allows users to login only once and then generates access tickets so that the users are allowed to access other services. Some configuration is necessary to use external authentication.

Built-in roles:

  • read: collStats, dbHash, dbStats, find, killCursors, listIndexes, listCollections 
  • readWrite: All read privileges + convertToCapped, createCollection, dbStats, dropCollection, createIndex, dropIndex, emptycapped, insert, listIndexes, remove, renameCollectionSameDB, update.  
  • readAnyDatabase: Allows the user to perform read in any database except the local and the config databases.

And so on…

In this tutorial, we are going to give specific privileges to a user who is allowed to only read the database, although he is allowed to write in a specific collection.

For this tutorial, we are using MongoDB 3.4 with previously configured authentication.

Steps:

  1. Create the database:
    mongo --authenticationDatbase admin -u superAdmin -p
    use percona
    db.foo.insert({x : 1})
    db.foo2.insert({x : 1})
  2. Create a new user:
    > db.createUser({user : 'client_read', pwd : '123', roles : ['read']})
    Successfully added user: { "user" : "client_read", "roles" : [ "read" ] }
  3. Log in with the user that has just been created and check the user access:
    ./mongo localhost/percona -u client_read -p
    MongoDB shell version v3.4.0-rc5
    Enter password:
    db.foo.find()
    { "_id" : ObjectId("586bc2e9cac0bbb93f325d11"), "x" : 1 }
    db.foo2.find().count()
    1
    // If user try to insert documents will receive an error:
    > db.foo.insert({x : 2})
    WriteResult({
                "writeError" : {
                "code" : 13,
                "errmsg" : "not authorized on percona to execute command
                     { insert: "foo", documents: [ { _id: ObjectId('586bc36e7b114fb2517462f3'), x: 2.0 } ], ordered: true }"
                }
    })
  4. Log out and log in again with administrator user to create a new role for this user:
    mongo --authenticationDatabase admin -u superAdmin -p
    db.createRole({
    role : 'write_foo2_Collection',
    privileges : [ {resource : {db : "percona", collection : "foo2"}, actions : ["insert","remove"]}
    ],
    roles : ["read"]
    })
    db.updateUser('client_read', roles : ['write_foo2_Collection'])
  5. Check the new access:
    ./mongo
    db.auth('client_read','123')
    1
    > show collections
    foo
    foo2
    > db.foo.find()
    { "_id" : ObjectId("586bc2e9cac0bbb93f325d11"), "x" : 1 }
    > db.foo2.insert({y : 2})
    WriteResult({ "nInserted" : 1 })
    > db.foo.insert({y : 2}) //does not have permission.
    WriteResult({
          "writeError" : {
                "code" : 13,
                "errmsg" : "not authorized on percona to execute command { insert: "foo", documents: [ { _id: ObjectId('586bc5e26f05b3a5db849359'), y: 2.0 } ], ordered: true }"
                         }
    })
  6. We can also add access to other database resources. Let’s suppose we would like to grant this just created user permission to execute a getLog command. This command is available in the clusterAdmin role, but we do not want to give all this role’s access to him. See here. There is a caveat/detail/observation here. If we want to grant cluster privileges to a user, we should create the role in the admin database. Otherwise, the command will fail:
    db.grantPrivilegesToRole(
         "write_foo2_Collection",
               [
                      {resource : {cluster : true}, actions : ["getLog"] }
               ]
    )
    Roles on the 'percona' database cannot be granted privileges that target other databases or the cluster :
  7. We are creating the same role in the admin database. This user only works properly if the admin database is present in a possible restore. Otherwise, the privileges fail:
    use admin
    db.createRole({
         role : 'write_foo2_Collection_getLogs',
         privileges : [
                           {resource : {db : "percona", collection : "foo2"}, actions : ["insert","remove"]},
                           {resource : {cluster : true}, actions : ["getLog"]}],  
         roles : [ {role : "read", db: "percona"}]
    })
    use percona
    db.updateUser( "client_read",
    {
         roles : [
              { role : "write_foo2_Collection_getLogs", db : "admin" }
                    ]
    }
    )
  8. Now the user has the same privileges as before, plus the getLog permission. We can test this user new access with:
    mongo --authenticationDatabase percona -u read_user -p
    db.adminCommand({getLog : 'global'})
    {
              "totalLinesWritten" : 287,
              "log" : [....
    ….
    }

I hope you find this post useful. 

authentication Database MongoDB

Published at DZone with permission of Adamo Tonete, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The 5 Books You Absolutely Must Read as an Engineering Manager
  • Multi-Cloud Integration
  • Required Knowledge To Pass AWS Certified Solutions Architect — Professional Exam
  • 10 Best Ways to Level Up as a Developer

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: