Механизмы аутентификации: SCRAM и x.509
Учащиеся включат аутентификацию SCRAM-SHA-256, создадут пользователей базы данных и настроят аутентификацию на основе сертификатов x.509 для внутренней аутентификации кластера.
«Механизмы аутентификации: SCRAM и x.509» — бесплатный урок MongoDB Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения MongoDB Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс MongoDB Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Authentication Is Critical
By default, a freshly installed MongoDB instance listens on 0.0.0.0:27017 with no authentication required. Countless real-world breaches have resulted from developers leaving MongoDB exposed to the internet without auth enabled. Production deployments must always enable authentication so that only credentialed users and services can connect. MongoDB supports multiple authentication mechanisms — the two most important are SCRAM and x.509 certificates.
Enabling Authentication in mongod
Authentication is enabled by adding security.authorization: enabled to the mongod.conf configuration file (or passing --auth on the command line). Once enabled, every connection attempt must supply valid credentials. Before enabling auth on an existing deployment, always create an admin user first — otherwise you will lock yourself out.
# mongod.conf snippet
security:
authorization: enabled
# Or start mongod with --auth flag
# mongod --auth --dbpath /data/dbCreating the First Admin User
Connect to MongoDB without auth while it is still in unauthenticated mode (or in localhost exception mode) to create the first user. Grant them the userAdminAnyDatabase role so they can create additional users. Then enable --auth and reconnect with credentials. The localhost exception allows an unauthenticated localhost connection only until the first user is created.
// Connect without auth, create admin user first
use admin
db.createUser({
user: 'adminUser',
pwd: 'StrongPassword123!',
roles: [
{ role: 'userAdminAnyDatabase', db: 'admin' },
{ role: 'readWriteAnyDatabase', db: 'admin' }
]
})
// Reconnect with auth
// mongosh 'mongodb://adminUser:StrongPassword123!@localhost:27017'SCRAM: The Default Auth Mechanism
SCRAM (Salted Challenge Response Authentication Mechanism) is MongoDB's default password-based authentication protocol. MongoDB uses SCRAM-SHA-256 (the newer, stronger variant) by default. SCRAM avoids sending the actual password over the network — the client and server perform a cryptographic handshake using salted hashes. Clients automatically negotiate the strongest SCRAM variant the server supports.
// Explicitly connect with SCRAM in Node.js
const { MongoClient } = require('mongodb')
const client = new MongoClient(
'mongodb://myUser:myPassword@localhost:27017/mydb?authSource=admin',
{ authMechanism: 'SCRAM-SHA-256' } // default, usually omitted
)
await client.connect()Creating Application Users With Least Privilege
Each application service should have its own MongoDB user with only the permissions it needs. A read-only reporting service should only have the read role on the specific database. A write-heavy API should only have readWrite. Granting root or dbOwner to application accounts violates the principle of least privilege and amplifies breach impact.
// Read-only reporting user
use myApp
db.createUser({
user: 'reportingSvc',
pwd: 'SecurePass!456',
roles: [{ role: 'read', db: 'myApp' }]
})
// API service user with read/write access
db.createUser({
user: 'apiSvc',
pwd: 'AnotherPass!789',
roles: [{ role: 'readWrite', db: 'myApp' }]
})x.509 Certificate-Based Authentication
x.509 certificates provide stronger authentication than passwords by using cryptographic key pairs. A client presents a certificate signed by a trusted Certificate Authority (CA) instead of a username/password. MongoDB maps the certificate's Subject Distinguished Name (DN) to a MongoDB user. This is the preferred mechanism for internal cluster member authentication (replicaset nodes authenticating with each other).
Configuring x.509 in mongod.conf
To enable x.509, you must configure TLS (the underlying transport) and set security.clusterAuthMode: x509 for intra-cluster auth. For client auth, set net.tls.CAFile to your CA certificate so MongoDB can verify client certificates. This requires generating a CA, signing certificates for each member and client, and distributing them securely.
# mongod.conf for x.509 client + cluster auth
net:
tls:
mode: requireTLS
certificateKeyFile: /etc/ssl/server.pem
CAFile: /etc/ssl/ca.pem
security:
authorization: enabled
clusterAuthMode: x509Creating a User Mapped to an x.509 Certificate
When using x.509 client authentication, the MongoDB username must exactly match the Subject DN of the client certificate. Create the user in the $external database (not the regular admin or app database) since credentials are validated externally by the certificate, not by MongoDB's internal credential store.
// Create user mapped to certificate Subject DN
use $external
db.createUser({
user: 'CN=apiService,OU=services,O=MyCompany,L=Istanbul,C=TR',
roles: [{ role: 'readWrite', db: 'myApp' }]
})
// Connect using certificate in Node.js
const client = new MongoClient('mongodb://localhost:27017', {
tls: true,
tlsCertificateKeyFile: '/etc/ssl/client.pem',
tlsCAFile: '/etc/ssl/ca.pem',
authMechanism: 'MONGODB-X509'
})Comparing SCRAM and x.509
SCRAM is simpler to set up — create a user with username/password and connect. It is suitable for most application services and developer access. x.509 is more complex (requires PKI infrastructure) but provides stronger guarantees: no passwords to rotate or leak, certificate revocation lists (CRLs) for immediate access revocation, and is mandatory for replica set member authentication in high-security environments.
Rotating Passwords and Updating Users
MongoDB provides db.updateUser() to change an existing user's password without dropping and recreating the account. In Atlas, rotate credentials through the Atlas UI or API. When rotating, update your application's connection string before changing the password to avoid a window of broken connectivity. Use connection string URI environment variables so password rotation requires only an env update and application restart.
// Rotate password for an existing user
use admin
db.updateUser('apiSvc', {
pwd: 'NewStrongerPassword!2024'
})
// Or use changeUserPassword shorthand
db.changeUserPassword('apiSvc', 'NewStrongerPassword!2024')Viewing and Removing Users
Audit your MongoDB users regularly. Use db.getUsers() to list all users in a database and db.getUser('name') for details on a specific account, including their assigned roles. Remove stale or compromised accounts immediately with db.dropUser(). On Atlas, the Users section of the Database Access panel provides a central inventory of all users across all clusters.
// List all users in current database
use myApp
db.getUsers()
// Get details of a specific user
db.getUser('apiSvc')
// Remove a user
db.dropUser('oldReportingService')Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: SCRAM-SHA-256 is MongoDB's default password-based auth mechanism and suitable for most application use cases, x.509 certificates provide stronger cryptographic authentication and are preferred for cluster-member internal auth, and always create users with least-privilege roles — application accounts should never hold admin-level permissions. Next up we dive into Role-Based Access Control.
Часто задаваемые вопросы
Урок «Механизмы аутентификации: SCRAM и x.509» бесплатный?
Да — полный текст урока «Механизмы аутентификации: SCRAM и x.509» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс MongoDB Academy, подпишись на CoddyKit PRO. Курс MongoDB Academy содержит 4 уроков всего.
Чему я научусь в уроке «Механизмы аутентификации: SCRAM и x.509»?
Учащиеся включат аутентификацию SCRAM-SHA-256, создадут пользователей базы данных и настроят аутентификацию на основе сертификатов x.509 для внутренней аутентификации кластера. Ты практикуешь MongoDB Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать MongoDB Academy?
Предыдущий опыт не требуется. MongoDB Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Механизмы аутентификации: SCRAM и x.509»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке MongoDB Academy?
Да. Каждый урок MongoDB Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Механизмы аутентификации: SCRAM и x.509
- Управление доступом на основе ролей: встроенные и пользовательские роли
- Шифрование данных в состоянии покоя и TLS при передаче
- Шифрование полей на стороне клиента