MongoDB account and Rights Management and login in Python and Java

Source: Internet
Author: User
Tags mongoclient

This article mainly introduces the new account of MongoDB, the Rights Management (simple), and the login in Python,java and the default client.

The default MongoDB is no account rights management, that is, do not need a password to log in, you can have read and Write permissions (of course, restart the service still need to be executed in the local).
This for their own laboratory enough to use, but for open data to others use is not safe, not afraid to steal data, mainly afraid of some pig teammates to drop the db, if there is no disaster backup to cry too late.
For MongoDB permissions configuration, I look at the official documents and other people's notes are also the people who stepped on the pit, the trampled hole written out to everyone to see, reduce the number of people to trample the pit. The main step of the pit or focus on the landing of different languages, this aspect of information is relatively small.

First switch to the admin database
Use admin
Then create a superuser, where the values of user and PWD can be arbitrarily defined.

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

1 Db.createuser (2 {3 User: "Super_user", 4 pwd: "SUPER_USER_PAASSWD", 5 roles: [{role: "__system", DB: "Admi N "}]6}7)

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

We then created two new users, one with read and write permissions, and one that only reads.
Read-write access to all services and programs that need to write data, and read accounts to be used when viewing and aggregating data from colleagues.

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

 1 //New Read Account  2 db.createuser ( {  3      "User"  :   "Rouser",//Account name  4      "pwd":  "rouserpwd",//password  5       "CustomData"  : { 6         //notes  7         user_abs: "Read-only user for data  analysis "  8     }, 9     " Roles "  : [ 10         {11              role:  "Readanydatabase",//Read all databases 12              db:  "Admin" 13          } 14     ]15     },{ 16          w:  "Majority"  , 17          wtimeout: 5000 18     } 19 ) 20 //New read/write account 21 db.createuser ( { 22      "User"  :  "rwuser",//account name 23       "pwd":  "rwuser_pwd",//Password 24      "CustomData"  : { //note 25          user_abs: "read-write user for data  Extractor " 26     },27     " roles " : [  28         {29              role:  "Readwriteanydatabase",//Read and write all databases 30              db:  "Admin" 31          } 32     ]33     },{ 34          w:  "Majority"  , 35         wtimeout:  5000 36     } 37 )

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

After the completion of the creation, first check whether it is new, simple, is to look at the admin is not recorded in the user account you want:

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

1 db.getcollection ("System.users"). Find ({}) 2 3 //output: 4 //actual input: Db.getcollection (" System.users "). Find ({},{" credentials ": 0}) 5 { " _id " : " Admin.super_user ", " user "  :  "Super_user",  "db"  :  "admin",  "roles"  : [ {  "role"  :  "__system",  "db"  :  "admin"  } ] }6 {  "_id"  :  "Admin.rouser",   "User"  :  "rouser",  "db"  :  "admin",  "CustomData"  : {  "User_ ABS " : " Read-only user for data analysis " }, " Roles " : [  {  "Role"  :  "Readanydatabase",  "db"  :  "admin"  } ] }7 {   "_id"  :  "Admin.rwuser",  "user"  :  "rwuser",  "db"  :  "admin",  "CustomData"  : {  "User_abs"  :  "Read-write user for data extractor " }, " Roles " : [ {  "Role"  :  "Readwriteanydatabase",  "db"  :  "admin"  } ]  }

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

See the output of all the account information, OK, the next step is to restart the service, before restarting the service, you need to set the config file ' auth = True ', so that you will need to log in, otherwise nothing changed
Here is my config file, the last line is the command to reinstall the service, if it is not installed, use the--install parameter:

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

1 #存放数据目录 2 Dbpath=f:\featuresdata\data 3 #日志文件 4 logpath=f:\featuresdata\mongo.log 5 #Cache Size 6 wiredtigercachesizegb= 1 7 8 auth = True 9 Logappend = True10 Directoryperdb = true11 #执行13 # mongod--config "F:\FeaturesData\mongo.config" --servicename "MongoDB"--reinstall

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

So start after MONGO have permission, this time the login to use account password:
 mongo  -u super_user-p super_user_paasswd--authenticationdatabase admin 127.0.0.1/test  
where 127.0.0.1/test is the ip/database name to connect to the default database.

This time you can try to use a read-only account to delete the library or delete the collection, there will be a drop failed:MongoError:not authorized on the test to execute command

means that you do not have permission to delete, this time do not say delete, insert operation also can not do.

In addition to using the default client connection, we can also use driver in other languages to connect.

Consider using Python and Java two scenarios here
First consider the connection in Python, we use the URI login:

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

  1 try:# python 3.x 2     from urllib.parse import  Quote_plus 3 except importerror:# python 2.x 4     from  urllib import quote_plus 5 from pymongo import mongoclient 6   7  #Example  8 user =  ' user '  9 password =  ' password ' 10  host =  ' 127.0.0.1:27017 ' 11  #Code12  uri =  "mongodb://%s:%[email  protected]%s " %  (13     quote_plus (user),  quote_plus (password),  Host) 14 client = mongoclient (URI) 

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

Consider using Java login again (a little bit of a hassle):

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

 1 //This is my own package. Read the properties file class  2 import com.zjtj.yuanyifan.Util.PropertiesUtil;  3  4 import com.mongodb.basicdbobject; 5 import com.mongodb.mongoclient;  6 import com.mongodb.MongoCredential; 7 import com.mongodb.ServerAddress;  8 import com.mongodb.client.finditerable; 9 import com.mongodb.client.mongocollection ; 10 11 private mongocollection<document> getmongodbconnection ()  {12          //initializing MongoDB database connection, variable name I don't think I need to explain it 13          propertiesutil pu = new propertiesutil ();14          string vfdbname = pu.getpropstring ("Vehicle_features_db_name",   "VF");15         string vfdbip =  Pu.getpropstring ("Vehicle_featureS_db_ip ", " 127.0.0.1 ");16         string vfdbport  = pu.getpropstring ("Vehicle_features_db_port",  "27017");17          string vfdbuser = pu.getpropstring ("Vehicle_features_db_user",  "USER_HERE"); 18          string vfdbpwd  = pu.getpropstring (" Vehicle_features_db_pwd ", " Passwd_here "); 19         try  {20             21              ServerAddress sainfo = new  ServerAddress (vfdbip, integer.valueof (vfdbport));22              List<MongoCredential> mgauth = new ArrayList<> (23);              mgauth.add (Mongocredential.createcredential (Vfdbuser, " Admin ", Vfdbpwd.tochararray ()));24              mongocollection<document> mgdbc = new mongoclient (Sainfo,mgauth). GetDatabase ( Vfdbname). GetCollection ("Daily_features");25              string dbginfo = string.format ("connected to mongodb://%s:%s/%s/\n",  vfdbip, vfdbport, vfdbname);26              system.out.printf (Dbginfo);27              fcc_log.info (Dbginfo);28              return mgdbc;29         } catch  ( EXCEPTION&NBSP;EX)  {30             string errinfo =  "Error  while initializing MongoDB connection:  " + ex.getmessage ();31              system.err.println (ErrInfo);32              fcc_log.fatal (ErrInfo);33          }34     }

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>


MongoDB account and Rights Management and login in Python and Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.