Post List

2015년 8월 8일 토요일

MongoDB Study #14 User 관리

1. MongoDB 인증방식

MongoDB는 Schema가 없습니다.
(대부분의 RDBMS는 Schema 내에 Table, Index 등의 Object를 생성하여 관리합니다.)
User 계정은 인증 용도로 사용될 뿐 Object 명칭과는 상관이 없습니다.
MongoDB는 2가지 인증 방법을 제공합니다.

1.1 OS 인증방식

--bind_ip 옵션 : 접속을 허용한 IP-Address를 직접 지정
Kerberos 인증 방식 : Instance로 부터 인증 키를 발급 받은 후 접속하는 방법

1.2 DB 인증방식

User ID, PWD를 이용하여 인증

2. User Management Methods

MethodDescription 
 db.auth() 해당 User로 인증
 db.createUser() User 생성
 db.updateUser() User 수정
 db.changeUserPassword() 이미 생성된 User의 PWD 수정
 db.removeUser()User 삭제. deprecated.
 db.dropAllUsers()모든 User 삭제
 db.dropUser() User 삭제
 db.grantRolesToUser() Role 을 User에게 허용
 db.revokeRolesFromUser() User에게서 Role 박탈
 db.getUser() User 정보 조회
 db.getUSers() 모든 User 정보 조회

자세한 내용은 http://docs.mongodb.org/manual/reference/method/js-user-management/ 참조하세요.

3. User 관리 실습

use admin
show users // 현재 생성되어 있는 User가 없음

db.createUser( { user:"sys" , pwd:"mongo" , roles : [ "readWrite", "userAdminAnyDatabase" ] } )
Successfully added user: { "user" : "sys", "roles" : [ "readWrite", "userAdminAnyDatabase" ] }

db.auth( { user : "sys" , pwd : "mongo" } ) // 1 : 인증성공 , 0 : 인증 거부
1

show users
{
        "_id" : "admin.sys",
        "user" : "sys",
        "db" : "admin",
        "roles" : [
                {
                        "role" : "readWrite",
                        "db" : "admin"
                },
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ]
}

db.createUser( { user : "scott" , pwd : "tiger" , roles : [ "readWrite" , "userAdmin" , "dbAdmin" , "clusterAdmin" , "dbAdminAnyDatabase" ] } )
Successfully added user: {
        "user" : "scott",
        "roles" : [
                "readWrite",
                "userAdmin",
                "dbAdmin",
                "clusterAdmin",
                "dbAdminAnyDatabase"
        ]
}
db.dropUser("scott")
true
db.createUser( { user : "scott" , pwd : "tiger" , roles : [ "readWrite" , "userAdmin" , "dbAdmin" , "clusterAdmin" , "dbAdminAnyDatabase" , { role : "readWrite" , db : "test" } ] } ) // 특정 database 에 대한 권한 부여
Successfully added user: {
        "user" : "scott",
        "roles" : [
                "readWrite",
                "userAdmin",
                "dbAdmin",
                "clusterAdmin",
                "dbAdminAnyDatabase",
                {
                        "role" : "readWrite",
                        "db" : "test"
                }
        ]
}


db.auth( "scott" , "tiger"  )
1
db.changeUserPassword("scott" , "ttt")
db.system.users.find().pretty()
{
        "_id" : "admin.sys",
        "user" : "sys",
        "db" : "admin",
        "credentials" : {
                "SCRAM-SHA-1" : {
                        "iterationCount" : 10000,
                        "salt" : "SyRa1/ptuZSNbQKTHK/h3g==",
                        "storedKey" : "J6zTZYECPenxWKeTYMsEOtM1yTQ=",
                        "serverKey" : "4GYG5eMu6xnyIEexOb6zhAPjG4Y="
                }
        },
        "roles" : [
                {
                        "role" : "readWrite",
                        "db" : "admin"
                },
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ]
}
{
        "_id" : "admin.scott",
        "user" : "scott",
        "db" : "admin",
        "credentials" : {
                "SCRAM-SHA-1" : {
                        "iterationCount" : 10000,
                        "salt" : "pg8Ak2nu0zRirRnQV1LzJA==",
                        "storedKey" : "6tObLRTT1NR2YktpnWfKXYmQLG0=",
                        "serverKey" : "BDDx1N7pfW1Jt9apQF0Sgop4NCQ="
                }
        },
        "roles" : [
                {
                        "role" : "readWrite",
                        "db" : "admin"
                },
                {
                        "role" : "userAdmin",
                        "db" : "admin"
                },
                {
                        "role" : "dbAdmin",
                        "db" : "admin"
                },
                {
                        "role" : "clusterAdmin",
                        "db" : "admin"
                },
                {
                        "role" : "dbAdminAnyDatabase",
                        "db" : "admin"
                },
                {
                        "role" : "readWrite",
                        "db" : "test"
                }
        ]
}

db.system.users.remove( { user:"scott" } )

4. Roles

MongoDB에는 다 열거하기 힘들 정도로 많은 Built-in Role들이 있습니다.
추가로 User-defined Role을 추가 할 수도 있습니다.
자세한 설명은 ( http://docs.mongodb.org/manual/reference/built-in-roles/ ) 에서 확인이 가능합니다.

5. Database 인증 실습

MongoDB Instance 를 인증모드로 실행합니다.

mongod --dbpath c:/mongodb/test --auth

이제 예전 방식대로 접속을 했을 경우 권한이 없어서 아무 것도 할 수 없게 됩니다.

C:\>mongo
MongoDB shell version: 3.0.5
connecting to: test
> use test
switched to db test
> show collections
2015-08-08T15:37:47.622+0900 E QUERY    Error: listCollections failed: {
        "ok" : 0,
        "errmsg" : "not authorized on test to execute command { listCollections: 1.0 }",
        "code" : 13
}
    at Error (<anonymous>)
    at DB._getCollectionInfosCommand (src/mongo/shell/db.js:646:15)
    at DB.getCollectionInfos (src/mongo/shell/db.js:658:20)
    at DB.getCollectionNames (src/mongo/shell/db.js:669:17)
    at shellHelper.show (src/mongo/shell/utils.js:625:12)
    at shellHelper (src/mongo/shell/utils.js:524:36)
    at (shellhelp2):1:1 at src/mongo/shell/db.js:646
>

앞서 만들어둔 sys 계정으로 인증 후 작업을 해보겠습니다.

use admin
switched to db admin

db.auth("sys","mongo")
1

use test
switched to db test

show collections
bank
de
...​
tel_pos
transfer

db.pos.find()
Error: error: { "$err" : "not authorized for query on test.pos", "code" : 13 }

sys 계정에는 test db에 대한 검색권한이 없습니다.
test db의 검색권한이 있는 계정을 생성한 뒤, 그 계정으로 인증을 하고 시도해 보겠습니다.

use admin
switched to db admin

db.createUser( { user : "scott" , pwd : "tiger" , roles : [ "readWrite" , "userAdmin" , "dbAdmin" , "clusterAdmin" , "dbAdminAnyDatabase" , { role : "readWrite" , db : "test" } ] } )
Successfully added user: { ... }

use admin
switched to db admin

db.auth("scott","tiger")
1

use test
switched to db test

db.pos.find()
{ "_id" : "m01", "data_type" : NumberLong(1), "loc" : { "type" : "Point", "coordinates" : [ 127.1058, 37.5164 ] }, "name
" : [ "name=잠실역 2호선", "trans_type=지하철" ] }
...
{ "_id" : "m09", "data_type" : NumberLong(1), "loc" : { "type" : "Point", "coordinates" : [ 127.1225, 37.524 ] }, "name"
 : [ "name=카페", "trans_type=Resturant" ] }

db.getSiblingDB('test').emp.find()
{ "_id" : ObjectId("55c13bcd2a1c4137302b17f7"), "empno" : 7369, "ename" : "SMITH", "job" : "CLERK", "hiredate" : "17-12-
1980", "sal" : 800, "deptno" : 20 }
...
{ "_id" : ObjectId("55c2a391abfcc1e37aa34b43"), "empno" : 7369, "ename" : "LunaStar" }

이제 접속을 하면서 인증을 같이 하는 방법을 살펴보겠습니다.

C:\>mongo -u sys -p mongo admin
MongoDB shell version: 3.0.5
connecting to: admin
> show collections
system.indexes
system.users
system.version
> exit
bye

C:\>mongo -u scott -p tiger test
MongoDB shell version: 3.0.5
connecting to: test
2015-08-08T15:58:25.672+0900 E QUERY    Error: 18 Authentication failed.
    at DB._authOrThrow (src/mongo/shell/db.js:1271:32)
    at (auth):6:8
    at (auth):7:2 at src/mongo/shell/db.js:1271
exception: login failed
C:\>mongo -u scott -p tiger admin
MongoDB shell version: 3.0.5
connecting to: admin
> use test
switched to db test
> show collections
bank
...
transfer

scott 계정의 경우 test의 readWrite 권한은 있지만, 접속을 할 수 있는 권한이 없습니다.
그래서 scott 계정을 새로 생성했습니다.

먼저 mongod--auth 옵션없이 실행한 뒤
scott 계정을 삭제 후 새로 만드세요.

​db.dropUser("scott")
db.createUser( { user : "scott" , pwd : "tiger" , roles : [ { role : "readWrite" , db : "test" } , { role : "userAdmin" , db: "test" } , { role : "dbAdmin" , db: "test" } ] } )

다시 mongod--auth 옵션으로 실행하세요.
그런 뒤 다시 접속을 시도해봅니다.

C:\>mongo -u scott -p tiger test
MongoDB shell version: 3.0.5
connecting to: test
> db.getUsers()
[
        {
                "_id" : "test.scott",
                "user" : "scott",
                "db" : "test",
                "roles" : [
                        {
                                "role" : "readWrite",
                                "db" : "test"
                        },
                        {
                                "role" : "userAdmin",
                                "db" : "test"
                        },
                        {
                                "role" : "dbAdmin",
                                "db" : "test"
                        }
                ]
        }
]
> use admin
switched to db admin
> db.getUsers()
2015-08-08T17:08:15.953+0900 E QUERY    Error: not authorized on admin to execute command { usersInfo: 1.0 }
    at Error (<anonymous>)
    at DB.getUsers (src/mongo/shell/db.js:1342:15)
    at (shell):1:4 at src/mongo/shell/db.js:1342>


댓글 없음:

댓글 쓰기