Secure MongoDB Access with SSO, TLS, and Auditing
Secure MongoDB access with SSO while keeping databases off the public internet, authenticating with short-lived client certificates, and recording every query in the audit log.
Setup takes four steps: create a join token, configure the MongoDB server,
grant access through AlmaForge RBAC, and connect with native mongosh or MongoDB Compass.
Prerequisites
MongoDB CLI
On your computer, check whether mongosh is installed:
mongosh --version2.12.0If it is missing:
brew install mongosh...==> Summary...mongosh --version2.12.0Disable the shell's telemetry and update checks. Run these separately:
mongosh --nodb --quiet --eval 'config.set("enableTelemetry", false)'Setting "enableTelemetry" has been changedmongosh --nodb --quiet --eval 'config.set("updateURL", "")'Setting "updateURL" has been changedThe settings persist between sessions. For other operating systems, follow Install mongosh.
MongoDB server
On your computer, open a second terminal and SSH into the database
server. Replace <ssh-user> and <database-host> with your SSH
account and server address:
ssh <ssh-user>@<database-host>...[<ssh-user>@<database-host> ~]$On the database server, check that you can run administrator commands, then check the operating system and installed database package:
sudo -v# No output on success. A password prompt may appear first.grep -E '^(ID_LIKE|VERSION_ID)=' /etc/os-releaseID_LIKE="rhel centos fedora"VERSION_ID="9.8"rpm -q mongodb-org-servermongodb-org-server-9.0.2-1.el9.x86_64sudo -v must succeed. If MongoDB is not installed, install the mongodb-org-server
and mongodb-mongosh packages from MongoDB's repository before continuing.
This guide uses the mongod systemd service. For another distribution,
adapt the repository and package commands using the
MongoDB installation instructions.
AlmaForge CLI
On your computer, check whether alma is installed:
alma version --clientClient Version: v2026.1.0+<build>If the command is not found, install it and repeat the check:
curl -fL https://get.almaforge.com/install.sh | sh...==> AlmaForge installed successfullyalma version --clientClient Version: v2026.1.0+<build>The installer supports Linux and macOS on both amd64 and arm64. See CLI installation for package-specific options.
AlmaForge Cluster
On your computer, sign in to your cluster and check your permissions.
Get your cluster's hostname from its administrator. If you do not have
an AlmaForge cluster yet, complete the
standalone deployment before continuing.
Replace almaforge.example.com below with that hostname. Run the login command
and complete the sign-in in your browser:
alma login --proxy=almaforge.example.com:443...
> Profile URL: https://almaforge.example.com:443
Logged in as: [email protected]
Cluster: almaforge.example.com
Roles: admin
...
After signing in, check your account and roles:
alma status> Profile URL: https://almaforge.example.com:443
Logged in as: [email protected]
Cluster: almaforge.example.com
Roles: admin
...
In the status output, check that:
Clusternames the cluster you intend to configure.Logged in asshows your account.Rolesincludesadmin.
If admin is missing, ask a cluster administrator to grant that role,
then run alma logout and repeat
the login and status commands. Continue once Roles includes admin.
Step 1. Create AlmaForge join token
On your computer, create an AlmaForge join token. The database agent uses it to join your AlmaForge cluster:
alma create token --services=databaseToken created. client_id: <client-id> client_secret: <client-secret>You will copy client_id and client_secret into the agent configuration
in Step 2. They are valid for 30 minutes. If they expire before the agent
joins, create a new token and use its values.
Step 2. Configure the MongoDB server
Install and configure the agent
The agent is almad with its Database Service enabled. It
connects outward to your cluster on port 443 and carries connections
between users and MongoDB.
On the MongoDB server, check whether almad is installed:
almad versionAlmaForge v2026.1.0+<build>If the command is not found, install the AlmaForge package:
curl -fL https://get.almaforge.com/install.sh | sh...==> AlmaForge installed successfullyalmad versionAlmaForge v2026.1.0+<build>On an RPM-based system, the installer uses the RPM package and installs the
almad systemd service. It supports both amd64 and arm64.
The version command must succeed before you configure the agent.
For other Linux distributions, see
Linux package installation.
Already running an agent on this host?
Keep its existing settings and enable ALMA_DATABASE_SERVICE=true.
Preserve the other services and label selectors. The join credentials
must permit the database service. The local target created below
does not need a label selector.
On the MongoDB server, open the agent configuration:
sudoedit /etc/almaforge/almad.env# Your text editor opens.For a new agent, enter the settings below. Replace ALMA_PROXY with
your cluster's hostname and port 443. Set ALMA_CLIENT_ID and
ALMA_CLIENT_SECRET to the values from Step 1:
# Database Service agent on the MongoDB host.
# Install at /etc/almaforge/almad.env as root:root with mode 0600.
ALMA_PROXY=almaforge.example.com:443
# Printed by `alma create token --services=database`.
ALMA_CLIENT_ID=paste-client-id-here
ALMA_CLIENT_SECRET=paste-client-secret-here
ALMA_DATABASE_SERVICE=true
ALMA_SSH_SERVICE=false
# Agent labels, separate from the database's labels.
ALMA_LABELS=env=demo
Save the file and close the editor. Restrict it to root because it contains the join credentials:
sudo chown root:root /etc/almaforge/almad.env# No output on success.sudo chmod 0600 /etc/almaforge/almad.env# No output on success.Create the TLS certificates
The agent and MongoDB run on the same server. Their connection uses the
loopback interface (localhost, or 127.0.0.1), so this traffic stays
on that server. A self-signed certificate for localhost is sufficient.
You do not need a public hostname or a certificate from a public CA.
MongoDB uses the AlmaForge database CA to verify client certificates presented by the agent.
Keep running these commands on the MongoDB server.
Download your cluster's public database CA. Replace almaforge.example.com
with your cluster's hostname:
curl -fsS -o almaforge-db-ca.pem 'https://almaforge.example.com:443/api/v1/auth/export?type=db'# No output on success.openssl x509 -in almaforge-db-ca.pem -noout# No output means the file contains a valid certificate.sudo install -d -o mongod -g mongod -m 0700 /etc/mongodbsudo install -o mongod -g mongod -m 0644 almaforge-db-ca.pem /etc/mongodb/server.cas# No output on success.Create a self-signed server certificate and private key for localhost,
then combine them into server.pem:
sudo openssl req -x509 -newkey rsa:2048 -nodes -days 3650 \ -subj '/CN=localhost' \ -addext 'subjectAltName=DNS:localhost,IP:127.0.0.1' \ -keyout /etc/mongodb/server.key -out /etc/mongodb/server.crt...-----sudo sh -c 'cat /etc/mongodb/server.crt /etc/mongodb/server.key > /etc/mongodb/server.pem'sudo rm -f /etc/mongodb/server.keysudo chown mongod:mongod /etc/mongodb/server.crt /etc/mongodb/server.pem# No output on success.sudo chmod 0600 /etc/mongodb/server.pem# No output on success.Enable TLS in MongoDB
Open /etc/mongod.conf on the server:
sudoedit /etc/mongod.conf# Your text editor opens.Configure net.tls for mutual TLS, authorization, and certificate authentication:
# Local TLS configuration on a dedicated MongoDB host.
# Configures mutual TLS using the local server certificate and AlmaForge database CA.
storage:
dbPath: /var/lib/mongo
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
net:
bindIp: 127.0.0.1
port: 27017
tls:
mode: requireTLS
certificateKeyFile: /etc/mongodb/server.pem
CAFile: /etc/mongodb/server.cas
allowConnectionsWithoutCertificates: true
security:
authorization: enabled
setParameter:
authenticationMechanisms: MONGODB-X509,SCRAM-SHA-256
Save the file and restart MongoDB:
sudo systemctl restart mongod# No output on success.systemctl is-active mongodactiveCreate the database account and sample data
On a fresh instance with no users, first create an administrator in the
admin database. MongoDB's localhost exception permits this first account.
If the instance already has an administrator, keep that account and skip
its creation.
sudo mongosh --quiet --host localhost --tls --tlsCAFile /etc/mongodb/server.crtAt the MongoDB prompt, create the administrator. passwordPrompt() asks
for a password without displaying it. Store it in your password manager:
use admin
db.createUser({
user: "admin",
pwd: passwordPrompt(),
roles: [{ role: "root", db: "admin" }]
});
exit
Connect again as the administrator. If using an existing account, replace
admin with its username and authentication database. Enter its password
at the prompt:
sudo mongosh --quiet --host localhost --tls --tlsCAFile /etc/mongodb/server.crt \ --username admin --authenticationDatabase admin --passwordAt the MongoDB prompt, create the certificate-authenticated CN=demo user
in $external and insert the sample data:
db.getSiblingDB("$external").createUser({
user: "CN=demo",
roles: [{ role: "read", db: "demo" }]
});
db.getSiblingDB("demo").demo.insertMany([
{ _id: 1, name: "alice" },
{ _id: 2, name: "bob" },
{ _id: 3, name: "carol" }
]);
exit
Register MongoDB with the agent
Still on the MongoDB server, display the public server certificate:
sudo cat /etc/mongodb/server.crt-----BEGIN CERTIFICATE-----...-----END CERTIFICATE-----Copy the entire certificate, including the BEGIN and END lines.
The agent uses it to verify MongoDB. Then open the target configuration:
sudo install -d -o root -g root -m 0700 /etc/almaforge/almad.d# No output on success.sudoedit /etc/almaforge/almad.d/mongodb.yaml# Your text editor opens.For a new file, copy the following YAML. If the file already exists,
update the existing resource and preserve its other settings. Replace
<paste the complete server certificate here> with the certificate you
copied. Indent every certificate line by six spaces beneath caCert: |:
# Connect the local MongoDB TLS instance through AlmaForge.
# Replace the placeholder with the contents of /etc/mongodb/server.crt.
apiVersion: almaforge.com/v1
kind: DatabaseTarget
metadata:
name: mongodb
labels:
db: mongodb
env: prod
spec:
protocol: mongodb
uri: localhost:27017
tls:
caCert: |
<paste the complete server certificate here>
Check that the certificate includes both its BEGIN and END lines,
then save the file and close the editor. Restrict the file to root:
sudo chown root:root /etc/almaforge/almad.d/mongodb.yaml# No output on success.sudo chmod 0600 /etc/almaforge/almad.d/mongodb.yaml# No output on success.Start and check the agent
Enable the services at boot and start the agent:
sudo systemctl enable mongod almad...sudo systemctl restart almad# No output on success.systemctl is-active mongod almadactiveactiveBoth services must report active. If either fails, inspect its log:
sudo journalctl -u mongod -u almad -n 50 --no-pager...<date> <time> <database-host> almad[<pid>]: <log-message>...Resolve any reported errors before continuing. The agent reads the
target configuration at startup, so restart almad after
changing /etc/almaforge/almad.d/mongodb.yaml.
Step 3. Grant access
On your computer, confirm that the agent has registered the database:
alma get dbHost Name Protocol URI Labels Version---------------- --------------- -------------- ------------------- ------------------ --------<database-host> mongodb mongodb <database-uri> db=mongodb ... 2026.1.0Check that mongodb appears with protocol mongodb and your database
server in the Host column. If either is missing, see
Database is missing or has no host.
Download mongodb-access.yaml
and save it locally.
This role allows access to targets labeled db: mongodb using the
demo account. MongoDB maps that account's client certificate to
CN=demo in $external. Its MongoDB roles grant access to the sample
demo database. Everyone assigned this AlmaForge role uses that
account, while AlmaForge audit events identify the signed-in person.
# Access to the MongoDB target using its CN=demo account.
# MongoDB grants that account read access on the sample demo database.
apiVersion: almaforge.com/v1
kind: Role
metadata:
name: mongodb-access
spec:
allow:
databaseLabels:
db: mongodb
databaseUsers:
- demo
databaseNames:
- '*' # Allow client metadata commands. MongoDB grants limit data access to demo.
Apply the role:
alma apply -f mongodb-access.yamlrole 'mongodb-access' has been createdCreating the role does not assign it to anyone. To grant it to an SSO group, list your connectors:
alma get oidcKind Name------------- -----------OIDCConnector company-ssoFind the connector your team uses to sign in. Replace <connector-name>
with its name from the output, then open it in your text editor:
alma edit oidc/<connector-name># Your text editor opens. After saving your changes:oidc connector "<connector-name>" has been updatedUnder spec.claimsToRoles, find the entry for the group that should have
MongoDB access. Add mongodb-access to that entry's roles list. Preserve
the existing roles and mappings, including those that grant admin,
then save and close the editor. The command applies your changes.
If the group has no mapping yet, follow
OIDC role mapping
to add one.
Step 4. Connect
On your computer, sign out of saved sessions, then sign back in with an
account in the group granted access in Step 3 to get a session with the
new role. logout clears saved sessions for all clusters. Use your
cluster's hostname in the login command:
alma logoutLogged out all users from all proxies.alma login --proxy=almaforge.example.com:443...> Profile URL: https://almaforge.example.com:443 Logged in as: [email protected] Cluster: almaforge.example.com Roles: mongodb-access ...alma status> Profile URL: https://almaforge.example.com:443 Logged in as: [email protected] Cluster: almaforge.example.com Roles: mongodb-access ...Check that Roles includes mongodb-access. If it is missing, check
your SSO group membership and the mapping from Step 3 before continuing.
Connect to the sample database:
alma db connect --db-user=demo --db-name=demo mongodb...demo> db.runCommand({ connectionStatus: 1 }).authInfo.authenticatedUsers[ { user: 'CN=demo', db: '$external' } ]demo> db.demo.countDocuments()3The first command must show user CN=demo in $external. The second
must return 3. These results confirm certificate authentication and
access to the sample data through AlmaForge. Type exit to return
to your terminal.
Advanced configuration
GUI clients and scripts
For MongoDB Compass or a script, leave this command running:
alma proxy db --tunnel --db-user=demo --db-name=demo mongodbStarted authenticated tunnel for the MongoDB database "mongodb" in cluster "almaforge.example.com" on 127.0.0.1:54321....Use the local address and port it prints. In Compass, connect to
mongodb://127.0.0.1:54321/demo, replacing 54321 with that port.
Leave authentication and TLS disabled for this local connection. The
tunnel authenticates you to AlmaForge, and the agent authenticates
to MongoDB with the demo account's certificate.
Architecture
The database agent runs beside MongoDB and opens an outbound tunnel to the AlmaForge Proxy. MongoDB listens on localhost and trusts the agent's client certificates.
Troubleshooting
Database is missing or has no host
On the database server, check that /etc/almaforge/almad.d/mongodb.yaml
exists and ALMA_DATABASE_SERVICE=true is set in /etc/almaforge/almad.env.
The agent must reach your cluster on port 443. Inspect its log:
sudo journalctl -u almad -n 50 --no-pager...<date> <time> <database-host> almad[<pid>]: <log-message>...Restart almad after correcting its configuration, then repeat
alma get db on your computer.
Access is denied
Run alma status and check for mongodb-access. If it is
missing, verify the SSO group mapping from Step 3, then sign out and
back in. The role's database labels must match the target file.
MongoDB cannot find the account
For an error mentioning CN=demo, check that the X.509 account exists
in $external and has permissions on demo. The setup creates that
account explicitly. When connecting through AlmaForge, use
--db-user=demo, without the CN= prefix.
Administrator creation fails
Use MongoDB's localhost exception or your existing database administrator to configure the X.509 account.
Certificate validation fails
/etc/mongod.conf must use /etc/mongodb/server.pem as
certificateKeyFile. That file contains both the server certificate
and its private key. CAFile must point to /etc/mongodb/server.cas,
the public AlmaForge database CA. The agent target's
spec.tls.caCert must contain /etc/mongodb/server.crt.
Limitations
- In this release, AlmaForge does not provision MongoDB users. Create
the X.509 account in
$externalbefore connecting, which you select with--db-user=demo. - Client-side authentication commands are rejected. Select the account when starting the tunnel, and leave client authentication disabled.
- MongoDB commands are checked against the role's
databaseNames. This example allows'*'so client metadata commands can run inadminas well asdemo. MongoDB's own grants restrict the account to reading the sample database.
References
- Database access overview: architecture and supported databases.
- RBAC reference: database access fields on a role.
- Declarative configuration: the
DatabaseTargetschema.