1.流程:

  (1)创建超级管理员

  (2)修改配置文件,验证身份登录

  (3)重启服务

  (4)使用超级管理员登录

  (5)创建普通用户

  (6)使用普通用户登录对应的数据库

mongodb数据库角色:

mongodb安全-LMLPHP

1创建用户:(只要指明角色和授予的数据库)

创建用户:(注意切换到admin数据库:)

> use admin
switched to db admin
> db.createUser({"user":"root",pwd:"",roles:[{role:"root",db:"admin"}]})
Successfully added user: {
"user" : "root",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}

 2.修改配置文件,启动验证身份:

  • linux下面修改/etc/mongod.conf (注意后面有空格)

mongodb安全-LMLPHP

重启服务即可

  • windows下面:  在启动mongod的时候后面携带--auth 参数,其中参数有很多,在最后会附上启动参数。
mongod --auth

  如果需要制定数据路径:

mongod --auth --dbpath c:\data\db

  因此可以将上面命令写入一bat脚本。(前提是将mongod的目录配置到环境变量path)

例如我的一个bat脚本:(我的安装目录是E:\mongodb\mongodb-win32-x86_64-enterprise-windows-64-3.6.3\bin)

e:
cd E:\mongodb\mongodb-win32-x86_64-enterprise-windows--3.6.\bin
mongod.exe --auth --dbpath c:\data\db
pause

 3.登录数据库:(需要制定数据库和密码)

直接登录:

mongo -u root -p  --authenticationDatabase admin

  这是以管理员身份登录,登录之后可以对任何数据库进行操作

因此将上面命令也可以写成一个脚本:

e:
cd E:\mongodb\mongodb-win32-x86_64-enterprise-windows--3.6.\bin
mongod.exe --auth --dbpath c:\data\db
pause

4.实际开发中是超级管理员创建一普通账户并给其分配对应的数据库,因此此用户只能操作其对应的数据库

  • 创建普通用户(对mydb数据库具有读写权限,账号密码都是user)
db.createUser({
"user":"user",
"pwd":"user",
roles:[{
"role":"readWrite",
"db":"mydb"
}]
})

mongodb安全-LMLPHP

  • 重启服务之后测试:
C:\Users\liqiang>mongo -u user -p user --authenticationDatabase admin  #普通用户登录admin数据库报错
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.
--26T22::07.191+ E QUERY [thread1] Error: Authentication failed.
:
DB.prototype._authOrThrow@src/mongo/shell/db.js::
@(auth)::
@(auth)::
exception: login failed C:\Users\liqiang>mongo -u user -p user --authenticationDatabase mydb  #普通用户登录分配给他的mydb数据库正常
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.
MongoDB Enterprise > db
admin
MongoDB Enterprise > use mydb  #访问admin数据库报错
switched to db mydb
MongoDB Enterprise > show tables #访问mydb正常
mydb
MongoDB Enterprise >

附一些mongod启动参数:

C:\Users\liqiang>mongod/?
Invalid command: /?
Options: General options:
-h [ --help ] show this usage information
--version show version information
-f [ --config ] arg configuration file specifying
additional options
-v [ --verbose ] [=arg(=v)] be more verbose (include multiple times
for more verbosity e.g. -vvvvv)
--quiet quieter output
--port arg specify port number - by default
--bind_ip arg comma separated list of ip addresses to
listen on - localhost by default
--bind_ip_all bind to all ip addresses
--ipv6 enable IPv6 support (disabled by
default)
--listenBacklog arg (=) set socket listen backlog size
--maxConns arg max number of simultaneous connections
- by default
--logpath arg log file to send write to instead of
stdout - has to be a file, not
directory
--logappend append to logpath instead of
over-writing
--logRotate arg set the log rotation behavior
(rename|reopen)
--timeStampFormat arg Desired format for timestamps in log
messages. One of ctime, iso8601-utc or
iso8601-local
--redactClientLogData Redact client data written to the
diagnostics log
--pidfilepath arg full path to pidfile (if not set, no
pidfile is created)
--timeZoneInfo arg full path to time zone info directory,
e.g. /usr/share/zoneinfo
--keyFile arg private key for cluster authentication
--noauth run without security
--setParameter arg Set a configurable parameter
--transitionToAuth For rolling access control upgrade.
Attempt to authenticate over outgoing
connections and proceed regardless of
success. Accept incoming connections
with or without authentication.
--clusterAuthMode arg Authentication mode used for cluster
authentication. Alternatives are
(keyFile|sendKeyFile|sendX509|x509)
--networkMessageCompressors [=arg(=disabled)] (=snappy)
Comma-separated list of compressors to
use for network messages
--auth run with security
--clusterIpSourceWhitelist arg Network CIDR specification of permitted
origin for `__system` access.
--slowms arg (=) value of slow for profile and console
log
--slowOpSampleRate arg (=) fraction of slow ops to include in the
profile and console log
--profile arg =off =slow, =all
--cpu periodically show cpu and iowait
utilization
--sysinfo print some diagnostic system
information
--noIndexBuildRetry don't retry any index builds that were
interrupted by shutdown
--noscripting disable scripting engine
--notablescan do not allow table scans Windows Service Control Manager options:
--install install Windows service
--remove remove Windows service
--reinstall reinstall Windows service (equivalent
to --remove followed by --install)
--serviceName arg Windows service name
--serviceDisplayName arg Windows service display name
--serviceDescription arg Windows service description
--serviceUser arg account for service execution
--servicePassword arg password used to authenticate
serviceUser Replication options:
--oplogSize arg size to use (in MB) for replication op
log. default is % of disk space (i.e.
large is good) Master/slave options (old; use replica sets instead):
--master master mode
--slave slave mode
--source arg when slave: specify master as
<server:port>
--only arg when slave: specify a single database
to replicate
--slavedelay arg specify delay (in seconds) to be used
when applying master ops to slave
--autoresync automatically resync if slave data is
stale Replica set options:
--replSet arg arg is <setname>[/<optionalseedhostlist
>]
--replIndexPrefetch arg specify index prefetching behavior (if
secondary) [none|_id_only|all]
--enableMajorityReadConcern [=arg(=)] (=)
enables majority readConcern Sharding options:
--configsvr declare this is a config db of a
cluster; default port ; default
dir /data/configdb
--shardsvr declare this is a shard db of a
cluster; default port SSL options:
--sslOnNormalPorts use ssl on configured ports
--sslMode arg set the SSL operation mode
(disabled|allowSSL|preferSSL|requireSSL
)
--sslPEMKeyFile arg PEM file for ssl
--sslPEMKeyPassword arg PEM file password
--sslClusterFile arg Key file for internal SSL
authentication
--sslClusterPassword arg Internal authentication key file
password
--sslCAFile arg Certificate Authority file for SSL
--sslCRLFile arg Certificate Revocation List file for
SSL
--sslDisabledProtocols arg Comma separated list of TLS protocols
to disable [TLS1_0,TLS1_1,TLS1_2]
--sslWeakCertificateValidation allow client to connect without
presenting a certificate
--sslAllowConnectionsWithoutCertificates
allow client to connect without
presenting a certificate
--sslAllowInvalidHostnames Allow server certificates to provide
non-matching hostnames
--sslAllowInvalidCertificates allow connections to servers with
invalid certificates
--sslFIPSMode activate FIPS - mode at startup Storage options:
--storageEngine arg what storage engine to use - defaults
to wiredTiger if no data files present
--dbpath arg directory for datafiles - defaults to
\data\db\ which is C:\data\db\ based on
the current working drive
--directoryperdb each database will be stored in a
separate directory
--noprealloc disable data file preallocation - will
often hurt performance
--nssize arg (=) .ns file size (in MB) for new databases
--quota limits each database to a certain
number of files ( default)
--quotaFiles arg number of files allowed per db, implies
--quota
--smallfiles use a smaller default file size
--syncdelay arg (=) seconds between disk syncs (=never,
but not recommended)
--upgrade upgrade db if needed
--repair run repair on all dbs
--repairpath arg root directory for repair files -
defaults to dbpath
--journal enable journaling
--nojournal disable journaling (journaling is on by
default for bit)
--journalOptions arg journal diagnostic options
--journalCommitInterval arg how often to group/batch commit (ms) Auditing Options:
--auditDestination arg Destination of audit log output.
(console/syslog/file)
--auditFormat arg Format of the audit log, if logging to
a file. (BSON/JSON)
--auditPath arg full filespec for audit log file
--auditFilter arg filter spec to screen audit records Kerberos Options:
--sspiHostnameCanonicalization arg (=none)
DNS resolution strategy to use for
hostname canonicalization. May be one
of: {none, forward, forwardAndReverse} SNMP Module Options:
--snmp-subagent run snmp subagent
--snmp-master run snmp as master Encryption at rest options:
--enableEncryption Enable encryption at rest
--encryptionKeyFile arg File path for encryption key file
--encryptionCipherMode arg Cipher mode to use for encryption at
rest
--kmipRotateMasterKey Rotate master encryption key
--kmipKeyIdentifier arg KMIP unique identifier for existing key
to use
--kmipServerName arg KMIP server host name
--kmipPort arg KMIP server port (defaults to )
--kmipClientCertificateFile arg Client certificate for authenticating
to KMIP server
--kmipClientCertificatePassword arg Client certificate for authenticating
Mongo to KMIP server
--kmipServerCAFile arg CA File for validating connection to
KMIP server LDAP Module Options:
--ldapServers arg Comma separated list of LDAP servers on
format host:port
--ldapTransportSecurity arg (=tls) Transport security used between MongoDB
and remote LDAP server(none|tls)
--ldapBindWithOSDefaults Peform queries with the service
account's username and password
--ldapBindMethod arg (=simple) Authentication scheme to use while
connecting to LDAP. This may either be
'sasl' or 'simple'
--ldapBindSaslMechanisms arg (=DIGEST-MD5)
Comma separated list of SASL mechanisms
to use while binding to the LDAP server
--ldapTimeoutMS arg (=) Timeout for LDAP queries (ms)
--ldapQueryUser arg LDAP entity to bind with to perform
queries
--ldapQueryPassword arg Password to use while binding to the
LDAP server to perform queries
--ldapUserToDNMapping arg (=[{match: "(.+)", substitution: "{0}"}])
Tranformation from MongoDB users to
LDAP user DNs
--ldapAuthzQueryTemplate arg Relative LDAP query URL which will be
queried against the host to acquire
LDAP groups. The token {USER} will be
replaced with the mapped username WiredTiger options:
--wiredTigerCacheSizeGB arg maximum amount of memory to allocate
for cache; defaults to / of physical
RAM
--wiredTigerJournalCompressor arg (=snappy)
use a compressor for log records
[none|snappy|zlib]
--wiredTigerDirectoryForIndexes Put indexes and data in different
directories
--wiredTigerCollectionBlockCompressor arg (=snappy)
block compression algorithm for
collection data [none|snappy|zlib]
--wiredTigerIndexPrefixCompression arg (=)
use prefix compression on row-store
leaf pages InMemory options:
--inMemorySizeGB arg maximum amount of memory to allocate
for InMemory data; defaults to % of
physical RAM less 1GB

附一些mongo的参数:

C:\Users\liqiang>mongo -help
MongoDB shell version v3.6.3
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
foo foo database on local machine
192.168.0.5/foo foo database on 192.168.0.5 machine
192.168.0.5:/foo foo database on 192.168.0.5 machine on port
Options:
--shell run the shell after executing files
--nodb don't connect to mongod on startup - no
'db address' arg expected
--norc will not run the ".mongorc.js" file on
start up
--quiet be less chatty
--port arg port to connect to
--host arg server to connect to
--eval arg evaluate javascript
-h [ --help ] show this usage information
--version show version information
--verbose increase verbosity
--ipv6 enable IPv6 support (disabled by
default)
--disableJavaScriptJIT disable the Javascript Just In Time
compiler
--disableJavaScriptProtection allow automatic JavaScript function
marshalling
--ssl use SSL for all connections
--sslCAFile arg Certificate Authority file for SSL
--sslPEMKeyFile arg PEM certificate/key file for SSL
--sslPEMKeyPassword arg password for key in PEM file for SSL
--sslCRLFile arg Certificate Revocation List file for
SSL
--sslAllowInvalidHostnames allow connections to servers with
non-matching hostnames
--sslAllowInvalidCertificates allow connections to servers with
invalid certificates
--sslFIPSMode activate FIPS - mode at startup
--retryWrites automatically retry write operations
upon transient network errors
--jsHeapLimitMB arg set the js scope's heap size limit Authentication Options:
-u [ --username ] arg username for authentication
-p [ --password ] arg password for authentication
--authenticationDatabase arg user source (defaults to dbname)
--authenticationMechanism arg authentication mechanism
--gssapiServiceName arg (=mongodb) Service name to use when authenticating
using GSSAPI/Kerberos
--gssapiHostName arg Remote host name to use for purpose of
GSSAPI/Kerberos authentication Kerberos Options:
--sspiHostnameCanonicalization arg (=none)
DNS resolution strategy to use for
hostname canonicalization. May be one
of: {none, forward, forwardAndReverse} file names: a list of files to run. files have to end in .js and will exit after
unless --shell is specified
05-26 18:29