node.js Connects to MongoDB through Privilege Verification

In January 2017, due to the negligence of the configuration of most mongodb, a series of cups and utensils happened. The so-called configuration negligence is that the owner of mongdb does not open authorization authentication for mongodb, resulting in the database "in any network environment, do not use account direct login". This thing tells us that we can't be too lazy, although sometimes the password set is the same as not set, but the password set is still to be set... So how do we open access authentication for mongodb? How to connect through node.js after opening authentication?
First, enter the bin directory of mongodb from the command line and connect to the database.

mongo --port 27017


Since I have now opened the permission, there is no problem with the output, but if you do not open the permission authentication, there will be a warning, do not believe you can try.
Adding users to mongodb is as follows

db.createUser({
    user:"User name",
    pwd:"Password",
    customData:"Description of this account",
    roles:[{role:"Role type",db:"Which database is the role created on?"},{role:"Role type",db:"Which database is the role created on?"},.....]
})

It is important to note that the values of roles parameters are an array. The roles are classified into four categories: database roles (read/readWrite/dbAdmin/dbOwner/user Admin), cluster roles (cluster Admin, etc.), backup roles (backup, etc.), and other special roles. As a super administrator, root is not known to which category. So take it out alone.
If we use show dbs on the command line of mongodb, we will find an admin database. If we create a user in this database, then the user can use the privileges of ta in all databases, such as reading and writing, which is the legendary global authentication.
Now we build a user named wopelo in admin library. Although we created a user, if we log in to mongodb again, we can access it without authentication. This is because we only created the user and did not open authorization authentication. It should be noted that mongodb can be accessed by default without authentication. Once the authentication is opened, the user name and password are needed to log in. Therefore, when we first create a user, we must first create a user and then open the authority authentication.
Opening permission authentication requires us to edit the mongod.conf file (which is not available on some computers, instead of mongod.config), and add auth=true at the end of the file.

After saving, we went back to mongodb and found that there was no need for authentication, but you could run a command (except the use command), and the command line would prompt for an error because of insufficient privileges.

So how to authenticate? We set up the DB field of roles when creating users, then we enter the corresponding database (so in the absence of authentication, use is a few commands available), using db.auth("user name", "password") to verify, the result is 1 success, 0 failure.
By doing this, we can validate the privileges on the command line, so how can we access the database through privileges in node.js?
Take the simplest and most primitive example.

var http=require("http");
var mongo=require("mongodb");
var querystring=require("querystring");
var nowPage;

var server=new mongo.Server("localhost",27017,{auto_reconnect:true});
var serverHttp=http.createServer();
serverHttp.listen(1337,"127.0.0.1");
serverHttp.on("listening",function(){
    console.log("Listening Starts");
});

var db=new mongo.Db("testDB",server,{safe:true});
serverHttp.on("request",function(req,res){
    if(req.url!="/favicon.ico"){
        console.log("Receive client request");
        console.log("Client Request Method:"+req.method+"\r\n");
        req.on("data",function(data){
            var iff=querystring.parse(decodeURIComponent(data));
            console.log(iff);
            if(iff.find){
                Find(res);
            }else if(iff.add){
                Add(res,iff);
            }else if(iff.updata){
                upData(res,iff);
            }else if(iff.remove){
                Remove(res,iff);
            }else if(iff.paging){
                Page(res,iff);
            }else if(iff.moving){
                Moving(res,iff);
            }
        });
        req.on("end",function(){
            console.log("Data Receiving Completed");
        });
    }
});

db.on("close",function(err,db){
    if(err){
        console.log("Closing Error"+err);
    }else{
        console.log("Successful database closure");
    }
});

function Find(x){
    console.log("Display data when pages are loaded");
    db.open(function(err,db){
        if(err){
            console.log("Connection error:"+err);
        }else{
            console.log("Successful connection to database");
            db.authenticate("wopelo","Password",function(){
                db.collection("Collections",function(err,collection){
                    collection.find({},{fields:{_id:0}}).toArray(function(err,docs){
                        if(err){
                            console.log("Query Error");
                        }else{
                            console.log("Number of data bars:"+docs.length);
                            var totalPage=Math.ceil(docs.length/7);
                            var totalMes=docs.length;
                            docs=docs.slice(0,7);
                            docs.push({"totalPage":totalPage});
                            docs.push({"totalMes":totalMes});
                            console.log(JSON.stringify(docs));
                            x.statusCode=200;
                            x.setHeader("Content-Type","text/plain");
                            x.setHeader("Access-Control-Allow-Origin","http://localhost");
                            x.write(JSON.stringify(docs));
                            x.end();
                            nowPage=1;
                        }
                        db.close();
                    });
                });
            });
        }
    });
}

The above code is just a fragment of a project, and it's not very mature, but you need to pay attention to it.
db.authenticate("wopelo", "password"), function(){}
This code is the key to using permission validation in node.js. But you need to pour cold water on everyone - so you still can't pass the authority certification, so why? That's why I bold the phrase "We now build a user named wopelo in admin library". Wopelo users are only based on admin library. Although users based on admin library can authenticate globally, the premise is that we must use admin database to authenticate first. Here we directly connect to testDB database. There is no user named wopelo in the whole database, so the best solution is to use admin database to authenticate globally. The solution is to create a user named wopelo in tesDB database with the same password as wopelo in admin, so that we can connect to testDB database.
Of course, the above chestnut is the most original way to connect to the database. We have other ways to connect and authenticate the privileges. If I have the chance to share with you later. Finally, it's the same old saying. You are welcome to criticize and correct it in the comments section below.

Keywords: Database MongoDB JSON network

Added by j4mes_bond25 on Tue, 02 Jul 2019 21:47:27 +0300