<p>MongoDB can be run in a secure mode where access to databases is controlled through name and password authentication. When run in this mode, any client application must provide a name and password before doing any operations. In the Java driver, you simply do the following with a MongoClient instance:</p>
<pre class="highlight">MongoClient mongoClient = new MongoClient(); 
DB db = mongoClient.getDB("test"); 
boolean auth = db.authenticate(myUserName, myPassword); 
</pre>
<p>If the name and password are valid for the database, auth will be true. Otherwise, it will be false. You should look at the MongoDB log for further information if available.</p>
<p>Most users run MongoDB without authentication in a trusted environment.In this tutorial, we show you how to start MongoDB in secure mode (authentication access is require), and uses Java driver to connect MongoDB with provided username and password.</p>
<h2><b>1. Start MongoDB in Secure Mode</b></h2>
<p>Create an user “<b>dineshonjava</b>” in MongoDB database “<b>dineshonjavaDB</b>”.</p>
<pre class="highlight">>; use dineshonjavaDB 
>; db.addUser("dineshonjava","password") 
</pre>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2013/01/auth.png" border="0" /></div>
<p>To start mongoDB in secure mode, just provide the <b>&#8220;–auth&#8221;</b> argument</p>
<pre class="highlight">>; mongod --auth 
</pre>
<div id="ads-id" align="center"></div>
<h2><b>2. Now, the MongoDB is started in secure /authentication mode (authenticate with username and password is require).</b></h2>
<p>if you try to access the auth db then we will get following.</p>
<pre class="highlight">>; db.auth("dineshonjava","password") 
1 
>; db.auth("dineshonjava","password1") 
Error: { errmsg: "auth fails", ok: 0.0 } 
0 
>; 
</pre>
<div class="separator" style="clear: both; text-align: center;"><img src="https://dineshonjava.com/wp-content/uploads/2013/01/auth1.png" border="0" /></div>
<h2><b>3. Java connect MongoDB</b></h2>
<p>In Java, you can use &#8220;<b>db.authenticate</b>&#8221; to handle the MongoDB authentication.</p>
<pre class="highlight">DB db = mongo.getDB("dineshonjavaDB"); 
boolean auth = db.authenticate("dineshonjava", "password".toCharArray()); 
</pre>
<p>If username and password is valid, &#8220;auth&#8221; will be true, else it will be false and return the following error pattern</p>
<pre class="highlight">com.mongodb.MongoException: unauthorized db:dineshonjavaDB lock type:-1 client:192.168.1.3 
 at com.mongodb.MongoException.parse(MongoException.java:82) 
 at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:302) 
 at com.mongodb.DBCursor._check(DBCursor.java:354) 
 at com.mongodb.DBCursor._hasNext(DBCursor.java:484) 
 at com.mongodb.DBCursor.hasNext(DBCursor.java:509) 
 at com.dineshonjava.mongo.test.MongoAuthDemo.main(MongoAuthDemo.java:24) 
 
</pre>
<p><b>See the full example as follows.</b></p>
<pre class="highlight">package com.dineshonjava.mongo.test; 
 
import java.net.UnknownHostException; 
 
import com.mongodb.DB; 
import com.mongodb.DBCollection; 
import com.mongodb.Mongo; 
import com.mongodb.MongoException; 
 
/** 
 * @author Dinesh Rajput 
 * 
 */ 
public class MongoAuthDemo { 
 
 public static void main(String[] args) { 
 
 try { 
 
 Mongo mongo = new Mongo("localhost", 27017); 
 DB db = mongo.getDB("dineshonjavaDB"); 
 boolean auth = db.authenticate("dineshonjava", "password".toCharArray()); 
 DBCollection collection = db.getCollection("empCollection"); 
 if(auth){ 
 System.out.println("TRUE"); 
 }else{ 
 System.out.println("FALSE"); 
 } 
 
 System.out.println("Done"); 
 
 } catch (UnknownHostException e) { 
 e.printStackTrace(); 
 } catch (MongoException e) { 
 e.printStackTrace(); 
 } 
 
 } 
 
} 
</pre>
<p>If everything is fine then we will get the following output-</p>
<div style="background-color: #ff99cc;"><b>output-</b><br />
TRUE<br />
Done</div>
<h2><b>Download Source Code + Libs</b><br />
<a href="https://sites.google.com/site/dinesh9582486434/my-forms/MongoDBAuthDemo.zip?attredirects=0&;d=1" target="_blank" rel="noopener"><b>MongoDBAuthDemo.zip</b></a></h2>
<p><b>References</b><br />
<a href="http://www.mongodb.org/display/DOCS/Java+Tutorial#JavaTutorial-Authentication%28Optional%29" target="_blank" rel="noopener"><b>MongoDB Java Authentication</b></a><br />
<a href="http://www.mongodb.org/display/DOCS/Security+and+Authentication" target="_blank" rel="noopener"><b>MongoDB Security and Authentication</b></a></p>
<div style="background-color: #ff99cc;"> <b> <;<;<a href="https://dineshonjava.com/java-mongodb-convert-json-data-to/">previous</a><;<; || <a href="https://dineshonjava.com/introduction-to-mongodb/">index </a>|| >;>;<a href="https://dineshonjava.com/spring-data-mongodb-examples/">next</a>>;>;</b></div>
<p> ;</p>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/spring-data-mongodb-examples/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/spring-data-mongodb-hello-world-example/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '585'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…