Authentication mechanisms (SCRAM, x.509, LDAP, etc.)
MongoDB provides multiple authentication mechanisms to ensure database security, including SCRAM, x.509 certificates, LDAP, and more. Different authentication methods are suitable for different scenarios, ranging from simple username/password verification to complex certificate-based or directory service-based identity management. Below is a detailed introduction to how these mechanisms work, their configuration methods, and practical application examples.
SCRAM Authentication
SCRAM (Salted Challenge Response Authentication Mechanism) is MongoDB's default authentication method, using usernames and passwords for identity verification. SCRAM employs salting and multiple rounds of hashing to protect passwords, effectively preventing replay attacks and password leaks.
SCRAM-SHA-1 and SCRAM-SHA-256
MongoDB supports two SCRAM algorithms:
SCRAM-SHA-1
(enabled by default)SCRAM-SHA-256
(requires explicit enabling)
Enable SCRAM-SHA-256 in the configuration file:
security:
authorization: enabled
scramIterationCount: 10000
setParameter:
authenticationMechanisms: "SCRAM-SHA-256,SCRAM-SHA-1"
Creating a SCRAM User
Create a SCRAM user via the Mongo Shell:
use admin
db.createUser({
user: "scramUser",
pwd: passwordPrompt(), // Interactive password input
roles: [ { role: "readWrite", db: "test" } ],
mechanisms: [ "SCRAM-SHA-256" ] // Specify the authentication mechanism
})
Frontend Connection Example
Connecting to a SCRAM-authenticated MongoDB using Node.js:
const { MongoClient } = require('mongodb');
async function connect() {
const uri = "mongodb://scramUser:password@localhost:27017/test?authMechanism=SCRAM-SHA-256";
const client = new MongoClient(uri);
try {
await client.connect();
console.log("Connected with SCRAM-SHA-256");
} finally {
await client.close();
}
}
connect().catch(console.error);
x.509 Certificate Authentication
x.509 certificate authentication uses TLS/SSL certificates for identity verification, making it suitable for high-security production environments. Each client must provide a valid certificate to connect to the database.
Certificate Preparation
The following files are required:
- CA certificate (ca.pem)
- Server certificate (server.pem)
- Client certificate (client.pem)
Example OpenSSL commands for generating certificates:
# Generate CA certificate
openssl req -x509 -newkey rsa:4096 -days 365 -nodes -keyout ca-key.pem -out ca.pem
# Generate server certificate
openssl req -newkey rsa:4096 -nodes -keyout server-key.pem -out server-req.pem
openssl x509 -req -in server-req.pem -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem
# Combine server certificate and private key
cat server-cert.pem server-key.pem > server.pem
MongoDB Configuration
Enable x.509 authentication in mongod.conf:
net:
tls:
mode: requireTLS
certificateKeyFile: /path/to/server.pem
CAFile: /path/to/ca.pem
security:
authorization: enabled
clusterAuthMode: x509
Creating an x.509 User
Create a user based on the certificate's DN (Distinguished Name):
use $external
db.createUser({
user: "CN=client,OU=users,O=example",
roles: [ { role: "readWrite", db: "test" } ]
})
Frontend Connection Example
Node.js connection using x.509 authentication:
const fs = require('fs');
const { MongoClient } = require('mongodb');
async function connect() {
const uri = "mongodb://localhost:27017/test?authMechanism=MONGODB-X509&tls=true";
const client = new MongoClient(uri, {
tls: true,
tlsCertificateKeyFile: '/path/to/client.pem',
tlsCAFile: '/path/to/ca.pem'
});
try {
await client.connect();
console.log("Connected with x.509");
} finally {
await client.close();
}
}
connect().catch(console.error);
LDAP Authentication
LDAP (Lightweight Directory Access Protocol) allows MongoDB to integrate with enterprise directory services for centralized identity management, making it suitable for organizations with existing LDAP infrastructure.
LDAP Configuration Preparation
The following information is required:
- LDAP server address
- Bind DN and password
- User search base DN
- User mapping rules
MongoDB Enterprise Edition Configuration
Configure LDAP in mongod.conf:
security:
authorization: enabled
ldap:
servers: "ldap.example.com"
transportSecurity: tls
bind:
queryUser: "cn=admin,dc=example,dc=com"
queryPassword: "password"
userToDNMapping: '[{ match: "(.+)", ldapQuery: "ou=users,dc=example,dc=com??sub?(uid={0})" }]'
authz:
queryTemplate: "{USER}?memberOf?base"
Creating LDAP-Mapped Roles
Create roles in MongoDB that map to LDAP groups:
use admin
db.createRole({
role: "ldapReadWrite",
privileges: [
{ resource: { db: "test", collection: "" }, actions: ["find", "insert", "update"] }
],
roles: []
})
db.runCommand({
createUser: "CN=ldapuser,OU=users,DC=example,DC=com",
roles: [ { role: "ldapReadWrite", db: "admin" } ],
writeConcern: { w: "majority" }
})
Frontend Connection Example
Node.js connection to an LDAP-authenticated MongoDB:
const { MongoClient } = require('mongodb');
async function connect() {
const uri = "mongodb://ldapuser@localhost:27017/test?authMechanism=PLAIN&authSource=$external";
const client = new MongoClient(uri);
try {
await client.connect();
console.log("Connected via LDAP");
} finally {
await client.close();
}
}
connect().catch(console.error);
Kerberos Authentication
MongoDB Enterprise Edition supports Kerberos authentication, which is suitable for enterprise environments with existing Kerberos deployments.
Kerberos Configuration
The following configurations are required:
- Keytab file
- Service Principal Name (SPN)
- Kerberos realm
Example mongod.conf configuration:
security:
authorization: enabled
kerberos:
keytab: /path/to/mongod.keytab
servicePrincipal: "mongodb/mongod.example.com@EXAMPLE.COM"
Creating a Kerberos User
After creating a principal in the Kerberos KDC, map it to MongoDB:
use $external
db.createUser({
user: "mongodbuser@EXAMPLE.COM",
roles: [ { role: "readWrite", db: "test" } ]
})
Frontend Connection Example
Node.js connection using Kerberos authentication:
const { MongoClient } = require('mongodb');
async function connect() {
const uri = "mongodb://mongodbuser%40EXAMPLE.COM@localhost:27017/test?authMechanism=GSSAPI&authSource=$external";
const client = new MongoClient(uri);
try {
await client.connect();
console.log("Connected via Kerberos");
} finally {
await client.close();
}
}
connect().catch(console.error);
Combining Multiple Authentication Mechanisms
MongoDB supports configuring multiple authentication mechanisms simultaneously, allowing clients to choose the appropriate method.
Example Combination Configuration
mongod.conf configuration:
security:
authorization: enabled
setParameter:
authenticationMechanisms: "SCRAM-SHA-256,MONGODB-X509,PLAIN,GSSAPI"
Connection String Examples
Specify different connection parameters based on the authentication mechanism:
// SCRAM connection
const scramUri = "mongodb://user:pass@host:27017/db?authMechanism=SCRAM-SHA-256";
// x.509 connection
const x509Uri = "mongodb://host:27017/db?authMechanism=MONGODB-X509&tls=true";
// LDAP connection
const ldapUri = "mongodb://ldapuser@host:27017/db?authMechanism=PLAIN&authSource=$external";
// Kerberos connection
const kerberosUri = "mongodb://user%40REALM@host:27017/db?authMechanism=GSSAPI&authSource=$external";
Performance Considerations for Authentication Mechanisms
Different authentication mechanisms have varying performance impacts:
- SCRAM: Moderate computational overhead (hashing)
- x.509: TLS handshake overhead, but session resumption can optimize
- LDAP: Depends on network latency; local caching is recommended
- Kerberos: Requires KDC interaction; ticket caching can improve performance
Command to monitor authentication performance:
db.runCommand({ serverStatus: 1 }).security.authentication
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:负载测试