1.流程:

  (1)创建超级管理员

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

  (3)重启服务

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

  (5)创建普通用户

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

mongodb数据库角色:

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

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

  1. > use admin
  2. switched to db admin
  3. > db.createUser({"user":"root",pwd:"",roles:[{role:"root",db:"admin"}]})
  4. Successfully added user: {
  5. "user" : "root",
  6. "roles" : [
  7. {
  8. "role" : "root",
  9. "db" : "admin"
  10. }
  11. ]
  12. }

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

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

重启服务即可

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

  如果需要制定数据路径:

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

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

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

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

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

直接登录:

  1. mongo -u root -p --authenticationDatabase admin

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

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

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

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

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

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

附一些mongod启动参数:

  1. C:\Users\liqiang>mongod/?
  2. Invalid command: /?
  3. Options:
  4.  
  5. General options:
  6. -h [ --help ] show this usage information
  7. --version show version information
  8. -f [ --config ] arg configuration file specifying
  9. additional options
  10. -v [ --verbose ] [=arg(=v)] be more verbose (include multiple times
  11. for more verbosity e.g. -vvvvv)
  12. --quiet quieter output
  13. --port arg specify port number - by default
  14. --bind_ip arg comma separated list of ip addresses to
  15. listen on - localhost by default
  16. --bind_ip_all bind to all ip addresses
  17. --ipv6 enable IPv6 support (disabled by
  18. default)
  19. --listenBacklog arg (=) set socket listen backlog size
  20. --maxConns arg max number of simultaneous connections
  21. - by default
  22. --logpath arg log file to send write to instead of
  23. stdout - has to be a file, not
  24. directory
  25. --logappend append to logpath instead of
  26. over-writing
  27. --logRotate arg set the log rotation behavior
  28. (rename|reopen)
  29. --timeStampFormat arg Desired format for timestamps in log
  30. messages. One of ctime, iso8601-utc or
  31. iso8601-local
  32. --redactClientLogData Redact client data written to the
  33. diagnostics log
  34. --pidfilepath arg full path to pidfile (if not set, no
  35. pidfile is created)
  36. --timeZoneInfo arg full path to time zone info directory,
  37. e.g. /usr/share/zoneinfo
  38. --keyFile arg private key for cluster authentication
  39. --noauth run without security
  40. --setParameter arg Set a configurable parameter
  41. --transitionToAuth For rolling access control upgrade.
  42. Attempt to authenticate over outgoing
  43. connections and proceed regardless of
  44. success. Accept incoming connections
  45. with or without authentication.
  46. --clusterAuthMode arg Authentication mode used for cluster
  47. authentication. Alternatives are
  48. (keyFile|sendKeyFile|sendX509|x509)
  49. --networkMessageCompressors [=arg(=disabled)] (=snappy)
  50. Comma-separated list of compressors to
  51. use for network messages
  52. --auth run with security
  53. --clusterIpSourceWhitelist arg Network CIDR specification of permitted
  54. origin for `__system` access.
  55. --slowms arg (=) value of slow for profile and console
  56. log
  57. --slowOpSampleRate arg (=) fraction of slow ops to include in the
  58. profile and console log
  59. --profile arg =off =slow, =all
  60. --cpu periodically show cpu and iowait
  61. utilization
  62. --sysinfo print some diagnostic system
  63. information
  64. --noIndexBuildRetry don't retry any index builds that were
  65. interrupted by shutdown
  66. --noscripting disable scripting engine
  67. --notablescan do not allow table scans
  68.  
  69. Windows Service Control Manager options:
  70. --install install Windows service
  71. --remove remove Windows service
  72. --reinstall reinstall Windows service (equivalent
  73. to --remove followed by --install)
  74. --serviceName arg Windows service name
  75. --serviceDisplayName arg Windows service display name
  76. --serviceDescription arg Windows service description
  77. --serviceUser arg account for service execution
  78. --servicePassword arg password used to authenticate
  79. serviceUser
  80.  
  81. Replication options:
  82. --oplogSize arg size to use (in MB) for replication op
  83. log. default is % of disk space (i.e.
  84. large is good)
  85.  
  86. Master/slave options (old; use replica sets instead):
  87. --master master mode
  88. --slave slave mode
  89. --source arg when slave: specify master as
  90. <server:port>
  91. --only arg when slave: specify a single database
  92. to replicate
  93. --slavedelay arg specify delay (in seconds) to be used
  94. when applying master ops to slave
  95. --autoresync automatically resync if slave data is
  96. stale
  97.  
  98. Replica set options:
  99. --replSet arg arg is <setname>[/<optionalseedhostlist
  100. >]
  101. --replIndexPrefetch arg specify index prefetching behavior (if
  102. secondary) [none|_id_only|all]
  103. --enableMajorityReadConcern [=arg(=)] (=)
  104. enables majority readConcern
  105.  
  106. Sharding options:
  107. --configsvr declare this is a config db of a
  108. cluster; default port ; default
  109. dir /data/configdb
  110. --shardsvr declare this is a shard db of a
  111. cluster; default port
  112.  
  113. SSL options:
  114. --sslOnNormalPorts use ssl on configured ports
  115. --sslMode arg set the SSL operation mode
  116. (disabled|allowSSL|preferSSL|requireSSL
  117. )
  118. --sslPEMKeyFile arg PEM file for ssl
  119. --sslPEMKeyPassword arg PEM file password
  120. --sslClusterFile arg Key file for internal SSL
  121. authentication
  122. --sslClusterPassword arg Internal authentication key file
  123. password
  124. --sslCAFile arg Certificate Authority file for SSL
  125. --sslCRLFile arg Certificate Revocation List file for
  126. SSL
  127. --sslDisabledProtocols arg Comma separated list of TLS protocols
  128. to disable [TLS1_0,TLS1_1,TLS1_2]
  129. --sslWeakCertificateValidation allow client to connect without
  130. presenting a certificate
  131. --sslAllowConnectionsWithoutCertificates
  132. allow client to connect without
  133. presenting a certificate
  134. --sslAllowInvalidHostnames Allow server certificates to provide
  135. non-matching hostnames
  136. --sslAllowInvalidCertificates allow connections to servers with
  137. invalid certificates
  138. --sslFIPSMode activate FIPS - mode at startup
  139.  
  140. Storage options:
  141. --storageEngine arg what storage engine to use - defaults
  142. to wiredTiger if no data files present
  143. --dbpath arg directory for datafiles - defaults to
  144. \data\db\ which is C:\data\db\ based on
  145. the current working drive
  146. --directoryperdb each database will be stored in a
  147. separate directory
  148. --noprealloc disable data file preallocation - will
  149. often hurt performance
  150. --nssize arg (=) .ns file size (in MB) for new databases
  151. --quota limits each database to a certain
  152. number of files ( default)
  153. --quotaFiles arg number of files allowed per db, implies
  154. --quota
  155. --smallfiles use a smaller default file size
  156. --syncdelay arg (=) seconds between disk syncs (=never,
  157. but not recommended)
  158. --upgrade upgrade db if needed
  159. --repair run repair on all dbs
  160. --repairpath arg root directory for repair files -
  161. defaults to dbpath
  162. --journal enable journaling
  163. --nojournal disable journaling (journaling is on by
  164. default for bit)
  165. --journalOptions arg journal diagnostic options
  166. --journalCommitInterval arg how often to group/batch commit (ms)
  167.  
  168. Auditing Options:
  169. --auditDestination arg Destination of audit log output.
  170. (console/syslog/file)
  171. --auditFormat arg Format of the audit log, if logging to
  172. a file. (BSON/JSON)
  173. --auditPath arg full filespec for audit log file
  174. --auditFilter arg filter spec to screen audit records
  175.  
  176. Kerberos Options:
  177. --sspiHostnameCanonicalization arg (=none)
  178. DNS resolution strategy to use for
  179. hostname canonicalization. May be one
  180. of: {none, forward, forwardAndReverse}
  181.  
  182. SNMP Module Options:
  183. --snmp-subagent run snmp subagent
  184. --snmp-master run snmp as master
  185.  
  186. Encryption at rest options:
  187. --enableEncryption Enable encryption at rest
  188. --encryptionKeyFile arg File path for encryption key file
  189. --encryptionCipherMode arg Cipher mode to use for encryption at
  190. rest
  191. --kmipRotateMasterKey Rotate master encryption key
  192. --kmipKeyIdentifier arg KMIP unique identifier for existing key
  193. to use
  194. --kmipServerName arg KMIP server host name
  195. --kmipPort arg KMIP server port (defaults to )
  196. --kmipClientCertificateFile arg Client certificate for authenticating
  197. to KMIP server
  198. --kmipClientCertificatePassword arg Client certificate for authenticating
  199. Mongo to KMIP server
  200. --kmipServerCAFile arg CA File for validating connection to
  201. KMIP server
  202.  
  203. LDAP Module Options:
  204. --ldapServers arg Comma separated list of LDAP servers on
  205. format host:port
  206. --ldapTransportSecurity arg (=tls) Transport security used between MongoDB
  207. and remote LDAP server(none|tls)
  208. --ldapBindWithOSDefaults Peform queries with the service
  209. account's username and password
  210. --ldapBindMethod arg (=simple) Authentication scheme to use while
  211. connecting to LDAP. This may either be
  212. 'sasl' or 'simple'
  213. --ldapBindSaslMechanisms arg (=DIGEST-MD5)
  214. Comma separated list of SASL mechanisms
  215. to use while binding to the LDAP server
  216. --ldapTimeoutMS arg (=) Timeout for LDAP queries (ms)
  217. --ldapQueryUser arg LDAP entity to bind with to perform
  218. queries
  219. --ldapQueryPassword arg Password to use while binding to the
  220. LDAP server to perform queries
  221. --ldapUserToDNMapping arg (=[{match: "(.+)", substitution: "{0}"}])
  222. Tranformation from MongoDB users to
  223. LDAP user DNs
  224. --ldapAuthzQueryTemplate arg Relative LDAP query URL which will be
  225. queried against the host to acquire
  226. LDAP groups. The token {USER} will be
  227. replaced with the mapped username
  228.  
  229. WiredTiger options:
  230. --wiredTigerCacheSizeGB arg maximum amount of memory to allocate
  231. for cache; defaults to / of physical
  232. RAM
  233. --wiredTigerJournalCompressor arg (=snappy)
  234. use a compressor for log records
  235. [none|snappy|zlib]
  236. --wiredTigerDirectoryForIndexes Put indexes and data in different
  237. directories
  238. --wiredTigerCollectionBlockCompressor arg (=snappy)
  239. block compression algorithm for
  240. collection data [none|snappy|zlib]
  241. --wiredTigerIndexPrefixCompression arg (=)
  242. use prefix compression on row-store
  243. leaf pages
  244.  
  245. InMemory options:
  246. --inMemorySizeGB arg maximum amount of memory to allocate
  247. for InMemory data; defaults to % of
  248. physical RAM less 1GB

附一些mongo的参数:

  1. C:\Users\liqiang>mongo -help
  2. MongoDB shell version v3.6.3
  3. usage: mongo [options] [db address] [file names (ending in .js)]
  4. db address can be:
  5. foo foo database on local machine
  6. 192.168.0.5/foo foo database on 192.168.0.5 machine
  7. 192.168.0.5:/foo foo database on 192.168.0.5 machine on port
  8. Options:
  9. --shell run the shell after executing files
  10. --nodb don't connect to mongod on startup - no
  11. 'db address' arg expected
  12. --norc will not run the ".mongorc.js" file on
  13. start up
  14. --quiet be less chatty
  15. --port arg port to connect to
  16. --host arg server to connect to
  17. --eval arg evaluate javascript
  18. -h [ --help ] show this usage information
  19. --version show version information
  20. --verbose increase verbosity
  21. --ipv6 enable IPv6 support (disabled by
  22. default)
  23. --disableJavaScriptJIT disable the Javascript Just In Time
  24. compiler
  25. --disableJavaScriptProtection allow automatic JavaScript function
  26. marshalling
  27. --ssl use SSL for all connections
  28. --sslCAFile arg Certificate Authority file for SSL
  29. --sslPEMKeyFile arg PEM certificate/key file for SSL
  30. --sslPEMKeyPassword arg password for key in PEM file for SSL
  31. --sslCRLFile arg Certificate Revocation List file for
  32. SSL
  33. --sslAllowInvalidHostnames allow connections to servers with
  34. non-matching hostnames
  35. --sslAllowInvalidCertificates allow connections to servers with
  36. invalid certificates
  37. --sslFIPSMode activate FIPS - mode at startup
  38. --retryWrites automatically retry write operations
  39. upon transient network errors
  40. --jsHeapLimitMB arg set the js scope's heap size limit
  41.  
  42. Authentication Options:
  43. -u [ --username ] arg username for authentication
  44. -p [ --password ] arg password for authentication
  45. --authenticationDatabase arg user source (defaults to dbname)
  46. --authenticationMechanism arg authentication mechanism
  47. --gssapiServiceName arg (=mongodb) Service name to use when authenticating
  48. using GSSAPI/Kerberos
  49. --gssapiHostName arg Remote host name to use for purpose of
  50. GSSAPI/Kerberos authentication
  51.  
  52. Kerberos Options:
  53. --sspiHostnameCanonicalization arg (=none)
  54. DNS resolution strategy to use for
  55. hostname canonicalization. May be one
  56. of: {none, forward, forwardAndReverse}
  57.  
  58. file names: a list of files to run. files have to end in .js and will exit after
  59. unless --shell is specified

mongodb安全的更多相关文章

  1. 【翻译】MongoDB指南/聚合——聚合管道

    [原文地址]https://docs.mongodb.com/manual/ 聚合 聚合操作处理数据记录并返回计算后的结果.聚合操作将多个文档分组,并能对已分组的数据执行一系列操作而返回单一结果.Mo ...

  2. 【翻译】MongoDB指南/CRUD操作(四)

    [原文地址]https://docs.mongodb.com/manual/ CRUD操作(四) 1 查询方案(Query Plans) MongoDB 查询优化程序处理查询并且针对给定可利用的索引选 ...

  3. 【翻译】MongoDB指南/CRUD操作(三)

    [原文地址]https://docs.mongodb.com/manual/ CRUD操作(三) 主要内容: 原子性和事务(Atomicity and Transactions),读隔离.一致性和新近 ...

  4. 【翻译】MongoDB指南/CRUD操作(二)

    [原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(二) 主要内容: 更新文档,删除文档,批量写操作,SQL与MongoDB映射图,读隔离(读关 ...

  5. 【翻译】MongoDB指南/CRUD操作(一)

    [原文地址]https://docs.mongodb.com/manual/ MongoDB CRUD操作(一) 主要内容:CRUD操作简介,插入文档,查询文档. CRUD操作包括创建.读取.更新和删 ...

  6. CRL快速开发框架系列教程十二(MongoDB支持)

    本系列目录 CRL快速开发框架系列教程一(Code First数据表不需再关心) CRL快速开发框架系列教程二(基于Lambda表达式查询) CRL快速开发框架系列教程三(更新数据) CRL快速开发框 ...

  7. MongoDB系列(二):C#应用

    前言 上一篇文章<MongoDB系列(一):简介及安装>已经介绍了MongoDB以及其在window环境下的安装,这篇文章主要讲讲如何用C#来与MongoDB进行通讯.再次强调一下,我使用 ...

  8. MongoDB系列(一):简介及安装

    什么是MongoDB MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统. 在高负载的情况下,添加更多的节点,可以保证服务器性能. MongoDB 旨在为应用提供可扩展的高 ...

  9. [原]分享一下我和MongoDB与Redis那些事

    缘起:来自于我在近期一个项目上遇到的问题,在Segmentfault上发表了提问 知识背景: 对不是很熟悉MongoDB和Redis的同学做一下介绍. 1.MongoDB数组查询:MongoDB自带L ...

  10. 用MongoDB分析合肥餐饮业

    看了<从数据角度解析福州美食>后难免心痒,动了要分析合肥餐饮业的念头,因此特地写了Node.js爬虫爬取了合肥的大众点评数据.分析数据库我并没有采用MySQL而是用的MongoDB,是因为 ...

随机推荐

  1. 玩转Vim-札记(二)

    玩转Vim-札记(二) 距上篇博文已有一周有余,上次主要介绍了编辑器之神Vim的起源.安装并介绍了两种模式以及一些简单的操作.本次将继续对Vim的使用进行介绍. 登堂入室 首先接着说移动吧: 0 → ...

  2. nodejs的交叉(跨平台)编译(to android)

    nodejs的二进制包有两种安装方式node-gyp以及node-pre-gyp 这两条命令会写入该包的安装脚本. node-gyp是使用gyp工具编译源码,因此必须指定交叉编译器(参见http:// ...

  3. C#异步了解一下

    如何让你的代码在“同一时间”干着两件件事呢?比如说,在初始化加载配置的同时,UI界面能够响应用户的各种点击事件.而不置于卡死,特别是出现如下面这种情况的时候,对于用户来说是很崩溃的.

  4. Spotlight on MySQL

    聚光灯在MySQL 1.Sessios会话Total Users:总用户数前连接到MySQL服务器的用户会话总数Active Users:活跃用户此控件表示连接到当前正在执行SQL语句或其他数据库请求 ...

  5. KVM WEB管理工具——WebVirtMgr(二)日常配置

    配置宿主机 1.登录WebVirtMgr管理平台 2.添加宿主机 选择首页的WebVirtMgr -->Addd Connection 选择“SSH链接“,设置Label,IP,用户 注意:La ...

  6. [Linux] 服务器镜像定时备份解决方案 crontab+rsync+flock

    两台服务器定时同步文件解决方案: 环境: 主机:192.168.1.1 镜像机:192.168.1.2 需要将主机内容备份至镜像机(假设用户都为root) 备份内容为 /export 目录下所有内容至 ...

  7. kinit

    su tf$ kinit -k -t /tmp/tf.keytab tf/admin@SINO.COM

  8. JQuery实现的智能表单提示

    实现一个类似如此效果的表单验证:

  9. php开发中处理emoji表情和颜文字的兼容问题

    背景:随着手机的普及,现在移动开发很火爆,已经远远超过了pc端.在移动设备经常会发生用户发送的内容中包含emoji表情,在显示时就是乱码.一般是因为Mysql表设计时,都是用UTF8字符集的.把带有e ...

  10. Qt5.6关联VS2013,配置VAssistX

    1. 安装Qt qt-creator-opensource-windows-x86-4.2.0.exe 2. 安装Qt VS插件 qt-vs-addin-1.2.5.exe 3. 配置ASSISTX ...