Skip to main content

๐Ÿ‘ RUN : Authentication challenge

info

The provided scripts are incomplete. Replace all <CODE_BLOCK> with the correct code to complete the lab.

Hint: Remember to add --projectId {project_id}

1. Create a SCRAM userโ€‹

# create a SCRAM user with username: "myUser", password: "mySecurePassword" and role: "readWriteAnyDatabase"
username = "myUser"
password = "mySecurePassword"
!atlas dbusers create <CODE_BLOCK>

Refer to documentations: atlas dbusers

tip
Answer
# create a SCRAM user with username: "myUser", password: "mySecurePassword" and role: "readWriteAnyDatabase"
username = "myUser"
password = "mySecurePassword"
!atlas dbusers create --username {username} --password {password} --role readWriteAnyDatabase --projectId {project_id}

2. Lets test our SCRAM user successful creation by performing the authentication processโ€‹

!pip install pymongo dnspython  
# retrieve connection string
connection = !atlas clusters connectionStrings describe MyNewCluster --projectId {project_id}

# add username and password to connection string
new_connection = connection[1].replace('mongodb+srv://', f'mongodb+srv://{username}:{password}@')
print(new_connection)

#make the connection get the list of databases
from pymongo import MongoClient
client = MongoClient(new_connection)
client.list_database_names()

3. Create a X509 user and certificateโ€‹

# create a Atlas-managed X509 user with username: "myX509User" and role: "readAnyDatabase" 
!atlas dbusers create <CODE_BLOCK>

Refer to documentations: atlas dbusers

# Generate a certification for "myX509user", set monthsUntilExpiration to 1, and save it to /tmp/cert.pem
!atlas dbusers certs create <CODE_BLOCK> > /tmp/cert.pem

Refer to documentations: atlas dbusers certs

tip
Answer
# create a Atlas-managed X509 user with username: "myX509User" and role: "readAnyDatabase" 
!atlas dbusers create --username myX509User --role readAnyDatabase --x509Type MANAGED --projectId {project_id}
# Generate a certification for "myX509user", set monthsUntilExpiration to 1, and save it to /tmp/cert.pem
!atlas dbusers certs create --username myX509User --monthsUntilExpiration 1 --projectId {project_id} > /tmp/cert.pem

4. Let's test our X509 Userโ€‹

# Get connection string
connection = !atlas clusters connectionStrings describe MyNewCluster --projectId {project_id}

# Modify connection string to use X509 as authentication mechanism
new_connection = connection[1].replace('.net', '.net?authSource=%24external&authMechanism=MONGODB-X509')
print(new_connection)

# Connect using the certificate
from pymongo import MongoClient
client = MongoClient(new_connection,
tlsCertificateKeyFile='/tmp/cert.pem')

# Access the database
client.list_database_names()

Next Stepsโ€‹

Start the chapter on RBAC for Role Based Access user management.