简体   繁体   中英

How to create MongoDB Authentication in Database?

I want to implement Authentication on MongoDB before accessing the database. Like in MYSQL, we have to create the username and password for specific database in PHP.

Now I want to implement the same protocols on MongoDB. I want to know how we can create the username and password for MongoDB Database so that when a request is generated from my node server then I have to pass the credential, without credential it has to generate the error. Any tutorial suggestion is really appreciated or someone has a better idea to share the things. I want only that my database is responded to only genuine or trusted server no other.

When using express you can create an authentication middleware. You can for example check for a valid json web token if using that implementation.

Syntax for accessing db would then be:

app.get(«/api/db», authMiddleware, async (req, res) => {
    const db = Db.find();
}

Where authMiddleware is an exported function you implement yourself based on what validation you want, and db is whatever db you trying to access, like categories or projects or something.

If you have multiple middlewares you can simply add them as an array, like this:

app.get(«/api/db», [middleware1, middleware2], async (req, res) => {})

With this you can for example check first if theres a logged in user, then you can check if that user is an admin. Note that this approach denies access to you api endpoint, but will therefore deny access to the database accessed through this endpoint.

db.createUser( { user: "user_name", pwd: "pass_word", roles: [ { role: "readWrite", db: "database_name" } ] } )

write the above query in your DB shell. But remember to use Build-in roles according to your use

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM