MongoDB 인증 추가하기

Jamie·2020년 12월 1일
1

MongoDB

목록 보기
2/8
post-thumbnail

선행작업 - Mongod 프로세스 올리기

$ mongod # mongod 프로세스 실행
$ ps -ef | grep mongod # process 확인
  501 44979 42188   0 10:39AM ttys001    0:11.18 mongod

MongoShell 다운로드 및 실행

$ mv ~/Download/mongosh-0.6.1-darwin.zip ~/Library/Mongo/

$ cd ~/Library/Mongo/
$ tar -zxvf mongosh-0.6.1-darwin.zip # 압축 해제

# 환경변수 등록하기 귀찮으니 기존 환경변수 경로로 이동시킴
$ mv mongosh mongodb-macos-x86_64-4.4.2/bin/
$ source ~/.bashrc

# 환경변수 등록된 덕에 바로 실행 가능
$ mongosh
Current sessionID:  5fc5a90f740611ee1acdde35
Connecting to:    mongodb://127.0.0.1:27017
Using MongoDB:      4.4.2
Using Mongosh Beta: 0.6.1

For more information about mongosh, please see our docs: https://docs.mongodb.com/mongodb-shell/


To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).
You can opt-out by running the disableTelemetry() command.

MongoDB Instance에 접근하기

$ mongo --host <HOSTNAME> --port <PORT>
$ mongo # hostname이 localhost고, port가 27017이라면 생략 가능
$ mongo
MongoDB shell version v4.4.2
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("5b37ac48-2c40-4f36-b725-304988d92486") }
MongoDB server version: 4.4.2
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
	https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
	https://community.mongodb.com
---
The server generated these startup warnings when booting: 
        2020-12-01T10:39:45.330+09:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
        2020-12-01T10:39:45.330+09:00: This server is bound to localhost. Remote systems will be unable to connect to this server. Start the server with --bind_ip <address> to specify which IP addresses it should serve responses from, or with --bind_ip_all to bind to all interfaces. If this behavior is desired, start the server with --bind_ip 127.0.0.1 to disable this warning
        2020-12-01T10:39:45.330+09:00: Soft rlimits too low
        2020-12-01T10:39:45.330+09:00:         currentValue: 256
        2020-12-01T10:39:45.330+09:00:         recommendedMinimum: 64000
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
> 
  • 위와 같이 접근하면 되는데 이게 mongosh랑 동일한 것 같긴 한데, 확실히 모르겠다. 조금 더 알아보기!

admin Database로 switch하기

> use admin
switched to db admin

root 사용자 생성

db.createUser(
  {
    user: "jamie",
    pwd: "jamie1234!!",
    roles: [ "root" ]
  }
)
# 엔터치면
Successfully added user: { "user" : "jamie", "roles" : [ "root" ] }
  • root role : 모든 리소스에 대한 권한
    • DB Query, Index 추가, 추가 사용자 생성, 배포 관리 등

사용자 확인

# mongo
> show users
{
	"_id" : "admin.jamie",
	"userId" : UUID("da759198-7169-4dff-b04c-cb9168fa6055"),
	"user" : "jamie",
	"db" : "admin",
	"roles" : [
		{
			"role" : "root",
			"db" : "admin"
		}
	],
	"mechanisms" : [
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}

# mongosh
> show users
[
  {
    _id: 'admin.jamie',
    userId: UUID("da759198-7169-4dff-b04c-cb9168fa6055"),
    user: 'jamie',
    db: 'admin',
    roles: [ { role: 'root', db: 'admin' } ],
    mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
  }
]
  • 생성된 계정 확인
  • mongosh가 조금 더 예쁘게 나오는 듯

서버 종료

> db.shutdownServer()
MongoNetworkError: connection 1 to 127.0.0.1:27017 closed

인증 사용 모드로 MongoDB 켜기

$ mongod --dbpath <path to data directory> --auth 
$ mongod --auth #/data/db인 경우 생략
{"t":{"$date":"2020-12-01T13:01:57.811+09:00"},"s":"I",  "c":"CONTROL",  "id":23285,   "ctx":"main","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"}
{"t":{"$date":"2020-12-01T13:01:57.813+09:00"},"s":"W",  "c":"ASIO",     "id":22601,   "ctx":"main","msg":"No TransportLayer configured during NetworkInterface startup"}
{"t":{"$date":"2020-12-01T13:01:57.814+09:00"},"s":"I",  "c":"NETWORK",  "id":4648602, "ctx":"main","msg":"Implicit TCP FastOpen in use."}
{"t":{"$date":"2020-12-01T13:01:57.814+09:00"},"s":"I",  "c":"STORAGE",  "id":4615611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":53190,"port":27017,"dbPath":"/data/db","architecture":"64-bit","host":"HSui-MacBookPro.local"}}
{"t":{"$date":"2020-12-01T13:01:57.814+09:00"},"s":"I",  "c":"CONTROL",  "id":23403,   "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"4.4.2","gitVersion":"15e73dc5738d2278b688f8929aee605fe4279b0e","modules":[],"allocator":"system","environment":{"distarch":"x86_64","target_arch":"x86_64"}}}}
{"t":{"$date":"2020-12-01T13:01:57.814+09:00"},"s":"I",  "c":"CONTROL",  "id":51765,   "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"Mac OS X","version":"18.7.0"}}}
{"t":{"$date":"2020-12-01T13:01:57.814+09:00"},"s":"I",  "c":"CONTROL",  "id":21951,   "ctx":"initandlisten","msg":"Options set by command line","attr":{"options":{"security":{"authorization":"enabled"}}}}
{"t":{"$date":"2020-12-01T13:01:57.817+09:00"},"s":"I",  "c":"STORAGE",  "id":22270,   "ctx":"initandlisten","msg":"Storage engine to use detected by data files","attr":{"dbpath":"/data/db","storageEngine":"wiredTiger"}}
{"t":{"$date":"2020-12-01T13:01:57.817+09:00"},"s":"I",  "c":"STORAGE",  "id":22315,   "ctx":"initandlisten","msg":"Opening WiredTiger","attr":{"config":"create,cache_size=3584M,session_max=33000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000,close_scan_interval=10,close_handle_minimum=250),statistics_log=(wait=0),verbose=[recovery_progress,checkpoint_progress,compact_progress],"}}
{"t":{"$date":"2020-12-01T13:01:58.439+09:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1606795318:439824][53190:0x115c8f5c0], txn-recover: [WT_VERB_RECOVERY_PROGRESS] Recovering log 2 through 3"}}
{"t":{"$date":"2020-12-01T13:01:58.508+09:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1606795318:508100][53190:0x115c8f5c0], txn-recover: [WT_VERB_RECOVERY_PROGRESS] Recovering log 3 through 3"}}
{"t":{"$date":"2020-12-01T13:01:58.605+09:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1606795318:604989][53190:0x115c8f5c0], txn-recover: [WT_VERB_RECOVERY | WT_VERB_RECOVERY_PROGRESS] Main recovery loop: starting at 2/7424 to 3/256"}}
{"t":{"$date":"2020-12-01T13:01:58.727+09:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1606795318:727725][53190:0x115c8f5c0], txn-recover: [WT_VERB_RECOVERY_PROGRESS] Recovering log 2 through 3"}}
{"t":{"$date":"2020-12-01T13:01:58.809+09:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1606795318:809373][53190:0x115c8f5c0], txn-recover: [WT_VERB_RECOVERY_PROGRESS] Recovering log 3 through 3"}}
{"t":{"$date":"2020-12-01T13:01:58.874+09:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1606795318:874791][53190:0x115c8f5c0], txn-recover: [WT_VERB_RECOVERY | WT_VERB_RECOVERY_PROGRESS] Set global recovery timestamp: (0, 0)"}}
{"t":{"$date":"2020-12-01T13:01:58.874+09:00"},"s":"I",  "c":"STORAGE",  "id":22430,   "ctx":"initandlisten","msg":"WiredTiger message","attr":{"message":"[1606795318:874857][53190:0x115c8f5c0], txn-recover: [WT_VERB_RECOVERY | WT_VERB_RECOVERY_PROGRESS] Set global oldest timestamp: (0, 0)"}}
{"t":{"$date":"2020-12-01T13:01:58.962+09:00"},"s":"I",  "c":"STORAGE",  "id":4795906, "ctx":"initandlisten","msg":"WiredTiger opened","attr":{"durationMillis":1145}}
{"t":{"$date":"2020-12-01T13:01:58.962+09:00"},"s":"I",  "c":"RECOVERY", "id":23987,   "ctx":"initandlisten","msg":"WiredTiger recoveryTimestamp","attr":{"recoveryTimestamp":{"$timestamp":{"t":0,"i":0}}}}
{"t":{"$date":"2020-12-01T13:01:58.962+09:00"},"s":"I",  "c":"STORAGE",  "id":4366408, "ctx":"initandlisten","msg":"No table logging settings modifications are required for existing WiredTiger tables","attr":{"loggingEnabled":true}}
{"t":{"$date":"2020-12-01T13:01:58.966+09:00"},"s":"I",  "c":"STORAGE",  "id":22262,   "ctx":"initandlisten","msg":"Timestamp monitor starting"}
{"t":{"$date":"2020-12-01T13:01:58.969+09:00"},"s":"W",  "c":"CONTROL",  "id":22140,   "ctx":"initandlisten","msg":"This server is bound to localhost. Remote systems will be unable to connect to this server. Start the server with --bind_ip <address> to specify which IP addresses it should serve responses from, or with --bind_ip_all to bind to all interfaces. If this behavior is desired, start the server with --bind_ip 127.0.0.1 to disable this warning","tags":["startupWarnings"]}
{"t":{"$date":"2020-12-01T13:01:58.970+09:00"},"s":"W",  "c":"CONTROL",  "id":22184,   "ctx":"initandlisten","msg":"Soft rlimits too low","attr":{"currentValue":256,"recommendedMinimum":64000},"tags":["startupWarnings"]}
{"t":{"$date":"2020-12-01T13:01:58.977+09:00"},"s":"I",  "c":"STORAGE",  "id":20536,   "ctx":"initandlisten","msg":"Flow Control is enabled on this deployment"}
{"t":{"$date":"2020-12-01T13:01:58.979+09:00"},"s":"I",  "c":"FTDC",     "id":20625,   "ctx":"initandlisten","msg":"Initializing full-time diagnostic data capture","attr":{"dataDirectory":"/data/db/diagnostic.data"}}
{"t":{"$date":"2020-12-01T13:01:58.980+09:00"},"s":"I",  "c":"NETWORK",  "id":23015,   "ctx":"listener","msg":"Listening on","attr":{"address":"/tmp/mongodb-27017.sock"}}
{"t":{"$date":"2020-12-01T13:01:58.980+09:00"},"s":"I",  "c":"NETWORK",  "id":23015,   "ctx":"listener","msg":"Listening on","attr":{"address":"127.0.0.1"}}
{"t":{"$date":"2020-12-01T13:01:58.980+09:00"},"s":"I",  "c":"NETWORK",  "id":23016,   "ctx":"listener","msg":"Waiting for connections","attr":{"port":27017,"ssl":"off"}}

인증하기

$ mongo # 또는
$ mongosh

> use admin
switched to db admin
> show users # 인증해야 사용 가능
MongoError: command usersInfo requires authentication

> db.auth("jamie", "jamie1234!!") # 인증
{ ok: 1 }

> show users # 사용 가능
[
  {
    _id: 'admin.jamie',
    userId: UUID("da759198-7169-4dff-b04c-cb9168fa6055"),
    user: 'jamie',
    db: 'admin',
    roles: [ { role: 'root', db: 'admin' } ],
    mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
  }
]

출처

MongoDB 공식 가이드 - https://docs.mongodb.com/guides/server/auth/

profile
성장중인 제이미입니다.

0개의 댓글