一步一步搭建react應用-mongodb開啓身份認證

[一步一步構建一個react應用-開篇](https://segmentfault.com/a/11...react

git地址git

  • 經過不認證的方式啓動Mongodbgithub

    mongod --port 3007  --config mongod.conf
  • mongo 鏈接實例 mongo --port 3307
  • 建立用戶超級管理員
use admin
db.createUser(
  {
    user: "myAdmin",
    pwd: "XXXXX",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)
  • 重啓mongodb,加上訪問控制
mongod --port 3007  --config mongod.conf --auth
  • 認證

鏈接時認證mongodb

mongo --port 3307 -u 'xxx' -p 'xxx' --authenticationDatabase "admin"

鏈接後認證segmentfault

mongo --port 3307

use admin

db.auth('username','pwd')

  • 爲其餘庫建立用戶
use movies
db.createUser(
  {
    user: "moviesAdmin",
    pwd: "XXXX",
    roles: [ { role: "readWrite", db: "movies" },
             { role: "read", db: "db2" } ]
  }
)
//添加user moviesAdmin,對movies有讀寫權限,對db2有讀權限

db.jsui

const {MongoClient,ObjectId} = require('mongodb')
const f = require('util').format
const user = encodeURIComponent('moviesAdmin')
const pwd = encodeURIComponent('xxxxx')
const authMechanism = 'DEFAULT'
let db_name='Movies'
if(process.env.NODE_ENV=='test'){
    db_name='Movies_test'
}
const url = f(`mongodb://%s:%s@localhost:3307/${db_name}?authMechanism=%s`, user, pwd, authMechanism)

module.exports = {
    connect() {
        return MongoClient.connect(url).catch(e=>{
            console.log(e)
        })
    },
    id(id) {
        try {
            if (id) {
                return new ObjectId(id)
            } else {
                return new ObjectId()
            }
        } catch (e) {

        }
    }
}
相關文章
相關標籤/搜索