Golo Roden
Golo Roden

Reputation: 150902

User not found on MongoDB Docker image with authentication

So I'm trying to setup a MongoDB using the official mongo Docker image, version 4.2.

What I want to achieve is to use the server with authentication enabled, and I want to have a custom database with a custom user and password.

So, I'm setting the following environment variables:

MONGO_INITDB_DATABASE: mydb
MONGO_INITDB_ROOT_USERNAME: jane
MONGO_INITDB_ROOT_PASSWORD: secret

In the documentation it states that if you provide the latter two environment variables, authentication is enabled automatically.

However, when I then try to access the mydb database using the credentials jane and secret, all I get is an error:

Supported SASL mechanisms requested for unknown user 'jane@mydb'
SASL SCRAM-SHA-1 authentication failed for jane on mydb from client 172.17.0.1:54702 ; UserNotFound: Could not find user "jane" for db "mydb"

Why is that? What am I missing?

My guess is that the user created only has access to the admin database, and I need to grant access for the user jane to the database mydb. I tried to do that using the following command:

mongo admin -u jane -p secret --eval "db.grantRolesToUser('jane', [{role: 'dbOwner', db: 'mydb'}])"

But this didn't work either. What am I missing?

Upvotes: 6

Views: 11646

Answers (1)

rokpoto.com
rokpoto.com

Reputation: 10794

You can authenticate with jane,secret against admin db, not mydb

Running mongo -u jane -p secret is equivalent to running mongo -u jane -p secret -authenticationDatabase admin. Check container logs to verify it.

MONGO_INITDB_DATABASE is for different purpose.

As docs state:

MONGO_INITDB_ROOT_USERNAME, MONGO_INITDB_ROOT_PASSWORD These variables, used in conjunction, create a new user and set that user's password. This user is created in the admin authentication database and given the role of root, which is a "superuser" role.

MONGO_INITDB_DATABASE This variable allows you to specify the name of a database to be used for creation scripts in /docker-entrypoint-initdb.d/*.js (see Initializing a fresh instance below). MongoDB is fundamentally designed for "create on first use", so if you do not insert data with your JavaScript files, then no database is created.

Initializing a fresh instance When a container is started for the first time it will execute files with extensions .sh and .js that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. .js files will be executed by mongo using the database specified by the MONGO_INITDB_DATABASE variable, if it is present, or test otherwise. You may also switch databases within the .js script.

Upvotes: 4

Related Questions