MongoDB 3.0 methods to create access control permissions and MongoDB GetLastError write security mechanism

Source: Internet
Author: User
Tags anonymous auth log log mongodb

MongoDB 3.0 Security Permission access control

MongoDB 3.0 access control has changed a lot, you need to pay attention to this parameter authenticationmechanisms. To use the 2.6 version, I directly specify the following parameters:

Setparameter:
Authenticationmechanisms:mongodb-cr
Parameter:
Authenticationmechanisms:mongodb-cr

Let's look at how to create access control permissions

Start MongoDB without using the-auth parameter


Mongodb-<a href= "http://www.ttlsa.com/linux/" title= "Linux" target= "_blank" >linux</a>-i686-3.0.0/bin/ Mongod-f mongodb-linux-i686-3.0.0/mongodb.conf

Mongodb-linux-i686-3.0.0/bin/mongod-f mongodb-linux-i686-3.0.0/mongodb.conf

At this point you show DBS will see that there is only one local database, the so-called admin does not exist.

MongoDB does not have super invincible user root, only can manage the user useradminanydatabase.
Add an Administrative user

Use admin
Db.createuser (
{
User: "Buru",
PWD: "12345678",
Roles: [{role: "Useradminanydatabase", DB: "admin"}]
}
)

Use admin
Db.createuser (
{
User: "Buru",
PWD: "12345678",
Roles: [{role: "Useradminanydatabase", DB: "admin"}]
}
)

The DB parameter in roles is required, otherwise it will be an error: Error:couldn ' t add user:missing expected field ' db '. In addition, there are many articles to record the use of Db.adduser (...) method, this method is old version, 3.0 no longer exist, see: Http://docs.mongodb.org/manual/reference/method/js-user-management.

Switch to admin to view the user you just created:
Show Users
Or
Db.system.users.find ()
{"_id": "Admin.buru", "User": "Buru", "db": "admin", "credentials": {"Scram-sha-1": {"IterationCount": 10000, "SA LT ":" gwvwua/dxvxgshavenlyva== "," Storedkey ":" l2qevteujpkcuqdekqfiwbsv4ms= "," Serverkey ":" M1ofnkxg2sncsfrbjbx4pxbsgvg= "}}," Roles ": [{" Role ":" Useradminanydatabase "," db ":" Admin "}]}

Show Users
Or
Db.system.users.find ()
{"_id": "Admin.buru", "User": "Buru", "db": "admin", "credentials": {"Scram-sha-1": {"IterationCount": 10000, "SA LT ":" gwvwua/dxvxgshavenlyva== "," Storedkey ":" l2qevteujpkcuqdekqfiwbsv4ms= "," Serverkey ":" M1ofnkxg2sncsfrbjbx4pxbsgvg= "}}," Roles ": [{" Role ":" Useradminanydatabase "," db ":" Admin "}]}

How do you close MongoDB? Never kill-9 pid, can kill-2 pid or db.shutdownserver ()

The following uses the-auth parameter to reboot the MongoDB:
Mongodb-linux-i686-3.0.0/bin/mongod--auth-f mongodb-linux-i686-3.0.0/mongodb.conf

Mongodb-linux-i686-3.0.0/bin/mongo
Use admin
Db.auth ("Buru", "12345678") #认证, return 1 to indicate success
Or
Mongodb-linux-i686-3.0.0/bin/mongo-u buru-p 12345678--authenticationdatabase Admin

Mongodb-linux-i686-3.0.0/bin/mongod--auth-f mongodb-linux-i686-3.0.0/mongodb.conf

Mongodb-linux-i686-3.0.0/bin/mongo
Use admin
Db.auth ("Buru", "12345678") #认证, return 1 to indicate success
Or
Mongodb-linux-i686-3.0.0/bin/mongo-u buru-p 12345678--authenticationdatabase Admin

Now show collections An error

2015-03-17t10:15:56.011+0800 E QUERY Error:listcollections failed: {
"OK": 0,
' ErrMsg ': ' not authorized in Admin to execute command {listcollections:1.0} '.
"Code": 13
}
At Error (<anonymous>)
At Db._getcollectioninfoscommand (src/mongo/shell/db.js:643:15)
At Db.getcollectioninfos (src/mongo/shell/db.js:655:20)
At Db.getcollectionnames (src/mongo/shell/db.js:666: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:643

2015-03-17t10:15:56.011+0800 E QUERY Error:listcollections failed: {
"OK": 0,
' ErrMsg ': ' not authorized in Admin to execute command {listcollections:1.0} '.
"Code": 13
}
At Error (<anonymous>)
At Db._getcollectioninfoscommand (src/mongo/shell/db.js:643:15)
At Db.getcollectioninfos (src/mongo/shell/db.js:655:20)
At Db.getcollectionnames (src/mongo/shell/db.js:666: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:643

Because the user Buru only the user-managed permissions.

The following creates the user, the user follows the library to walk, the user who creates is


Use Tianhe
Db.createuser (
{
User: "Bao",
PWD: "12345678",
Roles: [
{role: "ReadWrite", DB: "Tianhe"},
{role: "read", DB: "Tianhe2"}
]
}
)

Use Tianhe
Db.createuser (
{
User: "Bao",
PWD: "12345678",
Roles: [
{role: "ReadWrite", DB: "Tianhe"},
{role: "read", DB: "Tianhe2"}
]
}
)

View the user you just created.

Show Users

{
"_id": "Tianhe.bao",
"User": "Bao",
"DB": "Tianhe",
"Roles": [
{
"Role": "ReadWrite",
"DB": "Tianhe"
},
{
"Role": "read",
"DB": "Tianhe2"
}
]
}

Show Users

{
"_id": "Tianhe.bao",
"User": "Bao",
"DB": "Tianhe",
"Roles": [
{
"Role": "ReadWrite",
"DB": "Tianhe"
},
{
"Role": "read",
"DB": "Tianhe2"
}
]
}

View all users of the entire MONGODB:


Use admin
Db.system.users.find ()

{"_id": "Admin.buru", "User": "Buru", "db": "admin", "credentials": {"Scram-sha-1": {"IterationCount": 10000, "SA LT ":" gwvwua/dxvxgshavenlyva== "," Storedkey ":" l2qevteujpkcuqdekqfiwbsv4ms= "," Serverkey ":" M1ofnkxg2sncsfrbjbx4pxbsgvg= "}}," Roles ": [{" Role ":" Useradminanydatabase "," db ":" Admin "}]}
{"_id": "Tianhe.bao", "User": "Bao", "db": "Tianhe", "credentials": {"Scram-sha-1": {"IterationCount": 10000, "SA LT ":"//xy1v1fbqehc1gzqqzhgq== "," Storedkey ":" zs/o54zzl/fdcxlqj98kdavtff0= "," Serverkey ":" Iipnyz2gk8khyk3zgz6mubt0pi4= "}}," Roles ": [{Role]:" ReadWrite "," db ":" Tianhe "}, {" Role ":" read "," DB ":" Tianh E2 "}]}

Use admin
Db.system.users.find ()

{"_id": "Admin.buru", "User": "Buru", "db": "admin", "credentials": {"Scram-sha-1": {"IterationCount": 10000, "SA LT ":" gwvwua/dxvxgshavenlyva== "," Storedkey ":" l2qevteujpkcuqdekqfiwbsv4ms= "," Serverkey ":" M1ofnkxg2sncsfrbjbx4pxbsgvg= "}}," Roles ": [{" Role ":" Useradminanydatabase "," db ":" Admin "}]}
{"_id": "Tianhe.bao", "User": "Bao", "db": "Tianhe", "credentials": {"Scram-sha-1": {"IterationCount": 10000, "SA LT ":"//xy1v1fbqehc1gzqqzhgq== "," Storedkey ":" zs/o54zzl/fdcxlqj98kdavtff0= "," Serverkey ":" Iipnyz2gk8khyk3zgz6mubt0pi4= "}}," Roles ": [{Role]:" ReadWrite "," db ":" Tianhe "}, {" Role ":" read "," DB ":" Tianh E2 "}]}

Once created, verify that:


Use Buru
Show collections

2015-03-17t10:30:06.461+0800 E QUERY Error:listcollections failed: {
"OK": 0,
' ErrMsg ': ' Not authorized on Buru to execute command {listcollections:1.0} '.
"Code": 13
}
At Error (<anonymous>)
At Db._getcollectioninfoscommand (src/mongo/shell/db.js:643:15)
At Db.getcollectioninfos (src/mongo/shell/db.js:655:20)
At Db.getcollectionnames (src/mongo/shell/db.js:666: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:643

Use Buru
Show collections

2015-03-17t10:30:06.461+0800 E QUERY Error:listcollections failed: {
"OK": 0,
' ErrMsg ': ' Not authorized on Buru to execute command {listcollections:1.0} '.
"Code": 13
}
At Error (<anonymous>)
At Db._getcollectioninfoscommand (src/mongo/shell/db.js:643:15)
At Db.getcollectioninfos (src/mongo/shell/db.js:655:20)
At Db.getcollectionnames (src/mongo/shell/db.js:666: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:643

Obviously no authority, first Auth:


Db.auth ("Bao", "12345678")
1
Show collections
News
System.indexes
Wahaha

Db.auth ("Bao", "12345678")
1
Show collections
News
System.indexes
Wahaha


Mongodb GetLastError write security mechanism

First, Introduction

Many people complain that MongoDB is a memory database, there is no business, will not be safe, in fact, this is a misunderstanding of MongoDB, MongoDB has a complete redolog,binlog and persistence mechanism, do not worry too much about the loss of data.

Journal is the redo log in MongoDB, and Oplog is responsible for replicating binlog (corresponding to MySQL).

On the Google.groupuser, MONGO's developers have this explanation:

#########
By default:
Collection data (including Oplog) is fsynced to disk every.
Write operations are fsynced to journal file every.
Note, Oplog are available right away in memory for slaves to read. Oplog is a capped collection
So a new oplog are never created, old data just rolls off.
GetLastError with params:
(no params) = return after data updated in memory.
Fsync:true:
With--journal = wait for next fsync to journal file (up to milliseconds);
Without--journal = Force Fsync of collection data to disk then return.
W:2 = Wait for data to is updated in memory on at least two replicas.
########

You can see:

1, if open journal, then even if the power loss will only lose 100ms of data, which for most applications can be tolerated. The journal feature is turned on by default from 1.9.2+,MONGODB to ensure data security. and journal refresh time can be changed, 2-300ms range, using the--journalcommitinterval command.

2, Oplog and data refresh to disk Time is 60s, for replication, do not wait until Oplog refresh disk, in memory can be copied directly to the Sencondary node.

GetLastError Command

GetLastError is a MongoDB command, from the name, it seems to get the last error, but in fact it is mongodb a client blocking way. Use this command to obtain information about whether the write operation succeeded.

GetLastError has several parameters: J,w,fsync. In most language drivers, this command is packaged into Writeconcern classes, such as Java.

second, when to use this command:

1, MongoDB write operation by default is not any return value, which reduces the write operation waiting time, that is, whether there is no write to the disk or have encountered errors, it will not be an error. But generally we do not trust to do so, this time call the GetLastError command, get the return value.

Take Java as an example: when we set up a unique index for the field, we insert two identical data for the field, do not set Writerconcern or set the Writerconcern.normal mode, and you will not get any errors even if you throw an exception. The return value of the Insert () function in Java is the Writeresult class,

Writeresult (Commandresult O, Writeconcern concern) {
_lasterrorresult = O;
_lastconcern = concern;
_lazy = false;
_port = null;
_db = null;
}

Writeresult (Commandresult O, Writeconcern concern) {
_lasterrorresult = O;
_lastconcern = concern;
_lazy = false;
_port = null;
_db = null;
}

This class actually wraps the GetLastError return value, but at this point the Writeresult _lasterrorresult property is actually empty. Because the DUP key error is server error, the server error is only available in Writerconcern.safe or higher-level mode.

2. When reading and writing MongoDB in multithreaded mode, if these read and write operations are logically sequential, then it is also necessary to invoke the GetLastError command to ensure that the last operation is performed before the next operation, because the two-time connection may be different. In most cases, we will use the connection pool to connect to MongoDB, so this is a need to be noted.

For example: We encountered this exception before "the connection may have been used since this write, cannot obtain a result", the exception reason has two, the connection pool quantity is too small, the competition is too intense, does not have the setting writ Erconcern.safe.
See also: Https://groups.google.com/forum/?fromgroups=#!topic/mongodb-user/xzw0Cb831VY
PS: In Java and other languages, is not required to display the call to this command, only need to set Writerconcern can be.

third, GetLastError best practices

1, if there is no special requirements, the lowest level should also use Writerconcern.safe, that is, w=1.

2, for unimportant data, such as log log, you can use Writerconcern.none or writerconcern.normal, that is w=-1 or w=0, to save time waiting for the network.

3, a large number of discontinuous data writes, if each write calls GetLastError will degrade performance, because waiting for the network time is too long, in this case, you can call every n times GetLastError. However, in the Shard structure, this approach does not necessarily ensure that previous writes were successful.

4. For sequential Bulk writes (Batchs of write), to call GetLastError at the end of a bulk write, this will not only ensure that the last write is correct, but also ensure that all writes are reachable to the server. If you write tens of thousands of records consecutively without invoking GetLastError, you cannot ensure that all writes are successful in the same TCP socket. This can be problematic in the case of concurrency. To avoid this concurrency problem, you can refer to how to complete the bulk operation in a link (request), Url:java driver concurrency
Http://www.mongodb.org/display/DOCS/Java+Driver+Concurrency

5, the data security requirements are very high configuration: j=true,w= "Majority" Db.runcommand ({getlasterror:1,j:true,w: ' Majority ', wtimeout:10000})
The Java language can be set in Mongooption, and these settings in Mongooption are global and can be set separately for a single (join) operation.

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.