Error
Error Code:
13
MongoDB Error 13: Unauthorized Access Attempt
Description
MongoDB Error 13, 'Unauthorized', indicates that the authenticated user lacks the necessary permissions to perform a requested operation or access a specific resource. This typically occurs when a user tries to read, write, or administer a database without the required roles or privileges.
Error Message
Unauthorized
Known Causes
4 known causesIncorrect User Credentials
The provided username or password for authentication is incorrect or does not match any existing user in the authentication database.
Insufficient User Privileges
The authenticated user exists but does not have the required roles or permissions to perform the requested database operation (e.g., read, write, create collection).
Authentication Not Enabled
The MongoDB server is running without authentication enabled, but the client is attempting to connect with credentials, leading to an unexpected authorization failure.
Connecting to Wrong Database
The user is attempting to perform an action on a database for which they have no authorization, potentially due to connecting to the wrong database context.
Solutions
4 solutions available1. Grant Required Privileges medium
Give user permission for the operation
1
Connect as admin
mongosh --host localhost -u admin -p password --authenticationDatabase admin
2
Grant read/write on database
use admin
db.grantRolesToUser("myuser", [
{ role: "readWrite", db: "mydb" }
]);
3
Grant specific privileges
db.createRole({
role: "myCustomRole",
privileges: [
{ resource: { db: "mydb", collection: "" }, actions: ["find", "insert", "update", "remove"] }
],
roles: []
});
db.grantRolesToUser("myuser", [{ role: "myCustomRole", db: "admin" }]);
2. Check User Roles easy
Verify current permissions
1
Check user's roles
use admin
db.getUser("myuser")
2
Show role privileges
db.getRole("readWrite", { showPrivileges: true })
3. Create User with Correct Role easy
Create user with proper permissions
1
Create user with database access
use admin
db.createUser({
user: "appuser",
pwd: "password",
roles: [
{ role: "readWrite", db: "mydb" },
{ role: "read", db: "reporting" }
]
});
4. Fix Authentication Database easy
Authenticate against correct database
1
Check which database user was created in
use admin
db.system.users.find({ user: "myuser" })
2
Connect with correct authSource
mongosh "mongodb://user:pass@host/mydb?authSource=admin"