# MongoDB admin password

This tutorial will teach you how to provision MongoDB credentials using Vault.

### Setup MongoDB to be ready for Vault

#### Connect to the MongoDB instance

You can use the MongoDB shell to connect to your instance:

```bash
mongo
```

You can see the following warning when you enter their shell. Now you know you haven't provisioned a secret admin password.

```
WARNING: Access control is not enabled for the database.
         Read and write access to data and configuration is unrestricted.
```

#### Switch to the admin database

Once you are connected to the MongoDB shell, switch to the admin database:

```bash
use admin
```

#### Create the administrative user

Create a new administrative user for Vault by running the following command:

```bash
db.createUser({
  user: "vaultuser",
  pwd: "your_password_here",
  roles: [ { role: "root", db: "admin" } ]
})
```

This will create a new administrative user with the username `vaultuser` and password `your_password_here`. You can replace `your_password_here` with a strong password of your choice. The command should respond with `Successfully added user ...`.

#### Exit the MongoDB shell

Once you have created the administrative user, exit the MongoDB shell by running the following command:

```bash
exit
```

#### Restart MongoDB with authentication enabled

To enable authentication, you need to set `auth = true` in `/etc/mongodb.conf`

```bash
cat /etc/mongodb.conf | grep auth
sudo tee -a /etc/mongodb.conf <<< "auth = true"
cat /etc/mongodb.conf | grep auth
```

Now you can restart MongoDB. The exact steps for doing this will depend on your operating system and how you installed MongoDB. For example, on Linux systems that use systemd, you can use the following command:

```bash
sudo systemctl restart mongodb
```

### Setup Vault Database Secrets Engine for MongoDB

#### Starting the Dev Server

Start a Vault server in development mode (dev server). The dev server is a built-in, pre-configured server that is not very secure but useful for playing with Vault locally.

```bash
vault server -dev
```

#### Set environment variables

Then execute the following commands:

```bash
export VAULT_ADDR='http://127.0.0.1:8200'
export VAULT_TOKEN="$(cat ~/.vault-token)"
```

#### Verify the Server is Running

Verify the server is running by running the `vault status`{{exec}} command. If it runs successfully, the output should look like the following:

```bash
Key             Value
---             -----
Seal Type       shamir
Initialized     true
Sealed          false
Total Shares    1
Threshold       1
Version         1.13.1
Build Date      2023-03-23T12:51:35Z
Storage Type    inmem
Cluster Name    vault-cluster-141bcf10
Cluster ID      df9845ca-a0c1-d2b0-3eb7-45a845adfaee
HA Enabled      false
```

If the output looks completely different, restart the dev server and try again.

Congratulations! You've started your first Vault server.

#### Setup Database Secrets Engine for MongoDB

{% tabs %}
{% tab title="CLI" %}
**1. Enable the database secrets engine**

```bash
vault secrets enable database
```

**2. Configure Vault with the proper plugin and connection information**

```bash
vault write database/config/my-mongodb-database \
    plugin_name=mongodb-database-plugin \
    allowed_roles="my-role" \
    connection_url="mongodb://{{username}}:{{password}}@127.0.0.1:27017/admin" \
    username="vaultuser" \
    password="your_password_here"
```

**3. Configure a role that maps a name in Vault to a MongoDB command that executes and creates the database credential**

```bash
vault write database/roles/my-role \
    db_name=my-mongodb-database \
    creation_statements='{ "db": "admin", "roles": [{ "role": "readWrite" }] }' \
    default_ttl="1h" \
    max_ttl="24h"
```

If all of the above steps output with `Success! ...`, congratulations! You have now finished the Database Secrets Engine setup for MongoDB.
{% endtab %}

{% tab title="UI" %}

1. Go to the **`Secrets engine`** tab, click **`Enable new engine +`** , then select **`Databases`** to enable a new database engine.

   <figure><img src="https://1681203128-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZAOyClhisJhRvjIxLjXP%2Fuploads%2FDgbIqJbXBCWCKwSj1fn8%2Fimage.png?alt=media&#x26;token=e8c3dba6-6bec-4359-af17-bb2dc53eeff4" alt=""><figcaption></figcaption></figure>
2. Configure Vault with the proper plugin and connection information by clicking into the database engine and selecting **`Connect a database`**.

<figure><img src="https://1681203128-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZAOyClhisJhRvjIxLjXP%2Fuploads%2FZpq0MXfeAR3aQ3ZdpvHg%2Fimage.png?alt=media&#x26;token=15594c2c-2cde-4fa7-be0d-1dad100b45e7" alt=""><figcaption></figcaption></figure>

3. Type in the necessary information for the connection.

<figure><img src="https://1681203128-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZAOyClhisJhRvjIxLjXP%2Fuploads%2F49CikCnAO9TQJF5EM32p%2Fimage.png?alt=media&#x26;token=28b01b79-9459-4216-9e56-3f3d5240e6e0" alt=""><figcaption></figcaption></figure>

4. Go back, select the **`Roles`** Tab and click on **`Create role`**.

<figure><img src="https://1681203128-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZAOyClhisJhRvjIxLjXP%2Fuploads%2FBAXJqOhuRP38tiJ2PJB1%2Fimage.png?alt=media&#x26;token=eb721791-5f45-47bd-9da5-7c2dc1859c14" alt=""><figcaption></figcaption></figure>

5. Type in the necessary information for the role.

<figure><img src="https://1681203128-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZAOyClhisJhRvjIxLjXP%2Fuploads%2FJ6oFOVb3bM7lb6bB9f2x%2Fimage.png?alt=media&#x26;token=14cf744c-db87-4c60-94f5-96e58e69d218" alt=""><figcaption></figcaption></figure>
{% endtab %}
{% endtabs %}

### Verify everything works by login using Vault Secrets

#### Get credentials

After the secrets engine is configured and a user has a Vault token with the proper permission, it can generate credentials:

{% tabs %}
{% tab title="CLI" %}

```bash
vault read database/creds/my-role
```

{% endtab %}

{% tab title="UI" %}

<figure><img src="https://1681203128-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FZAOyClhisJhRvjIxLjXP%2Fuploads%2FHF76FM4ACxuEQFQnTnTw%2Fimage.png?alt=media&#x26;token=07d09222-8864-4f4e-97e0-8f0f639dac41" alt=""><figcaption></figcaption></figure>
{% endtab %}
{% endtabs %}

#### Connect to the MongoDB instance with generated credentials

Now you can use the generated credentials in order to perform administrative tasks.

We first get a usable credential from the command we just used above.

```bash
cat credential.txt
username=$(cat credential.txt | grep username | tr -s ' ' | cut -d' ' -f2)
password=$(cat credential.txt | grep password | tr -s ' ' | cut -d' ' -f2)
echo $username
echo $password
```

Then we can authenticate into the MongoDB database using the credential.

```bash
mongo -u "$username" -p "$password" --authenticationDatabase admin
```

Once you are authenticated, you can perform administrative tasks using the MongoDB shell, like creating a collection in the admin database:

```bash
use admin
db.createCollection("test2")
```

The command should work without any issues (respond with `{ "ok" : 1 }`).

#### Verify that we need authentication

Now, let's try to perform administrative tasks without authentication. Try to create a collection again in the admin database.

```bash
exit
mongo
use admin
db.createCollection("test3")
```

Since we didn't authenticate ourselves to the database, The command should fail with the following response:

```bash
{
    "ok" : 0,
    "errmsg" : "there are no users authenticated",
    "code" : 13,
    "codeName" : "Unauthorized"
}
```
