0
0
MongoDBquery~5 mins

Authentication mechanisms in MongoDB

Choose your learning style9 modes available
Introduction

Authentication mechanisms help verify who you are before you can use a database. This keeps data safe and private.

When you want to control who can see or change your data.
When multiple people or apps use the same database and need different access levels.
When you want to protect sensitive information from strangers.
When you connect to a database over the internet and need to be sure the user is trusted.
Syntax
MongoDB
db.auth(username, password)
This command is used inside the MongoDB shell to log in as a user.
You must have created the user with a username and password before using this.
Examples
This tries to log in as user 'alice' with the password 'mypassword'.
MongoDB
db.auth('alice', 'mypassword')
This tries to log in as user 'bob' with the password '12345'.
MongoDB
db.auth('bob', '12345')
Sample Program

This example first creates a user named 'testUser' with password 'testPass' and read/write access. Then it logs in as that user.

MongoDB
use admin
// Create a user
db.createUser({user: 'testUser', pwd: 'testPass', roles: ['readWrite']})

// Authenticate as the new user
db.auth('testUser', 'testPass')
OutputSuccess
Important Notes

Authentication must be enabled in MongoDB configuration to work.

Passwords are stored securely, so you cannot see them after creation.

Use roles to control what authenticated users can do.

Summary

Authentication checks who you are before allowing database access.

Use db.auth() to log in with a username and password.

Always create users with proper roles to keep data safe.