From Mongo Java Tutorial
MongoDB can be run in safe mode when access to databases is controlled by authentication by name and password. When launched in this mode, any client application must specify a name and password before performing any operations. In the Java driver, you simply do the following with the mongo object attached:
boolean auth = db.authenticate(myUserName, myPassword);
If the username and password are valid for the database, auth will be true. Otherwise, it will be wrong. You should look at the MongoDB log for more information, if any.
Most users run MongoDB without authentication in a trusted environment.
Configure Authentication and Security
Authentication is stored in each system.users database. For example, in the projectx project, the project projectx.system.users will contain information about the user.
First we need to configure an admin user for the entire db server process. This user is stored in a special admin database.
If no users are configured in admin.system.users, you can access the database from the localhost interface without authentication. Thus, from the server on which the database is running (and therefore on localhost), start the database shell and configure the administrative user:
$ ./mongo > use admin > db.addUser("theadmin", "anadminpassword")
Now the user has a database administrator. Please note that if we have not been authenticated yet, we must do this if we want to perform further operations, since there is a user in admin.system.users.
> db.auth("theadmin", "anadminpassword")
We can view existing users for the database using the command:
> db.system.users.find()
Now configure the "regular" user for a different database.
> use projectx > db.addUser("joe", "passwordForJoe")
Finally, add a read-only user. (only supported in 1.3.2 +)
> use projectx > db.addUser("guest", "passwordForGuest", true)