Categories: MongoDB

Authentication to MongoDB with Java

<p>MongoDB can be run in a secure mode where access to databases is controlled through name and password authentication&period; When run in this mode&comma; any client application must provide a name and password before doing any operations&period; In the Java driver&comma; you simply do the following with a MongoClient instance&colon;<&sol;p>&NewLine;<pre class&equals;"highlight">MongoClient mongoClient &equals; new MongoClient&lpar;&rpar;&semi; &NewLine;DB db &equals; mongoClient&period;getDB&lpar;"test"&rpar;&semi; &NewLine;boolean auth &equals; db&period;authenticate&lpar;myUserName&comma; myPassword&rpar;&semi; &NewLine;<&sol;pre>&NewLine;<p>If the name and password are valid for the database&comma; auth will be true&period; Otherwise&comma; it will be false&period; You should look at the MongoDB log for further information if available&period;<&sol;p>&NewLine;<p>Most users run MongoDB without authentication in a trusted environment&period;In this tutorial&comma; we show you how to start MongoDB in secure mode &lpar;authentication access is require&rpar;&comma; and uses Java driver to connect MongoDB with provided username and password&period;<&sol;p>&NewLine;<h2><b>1&period; Start MongoDB in Secure Mode<&sol;b><&sol;h2>&NewLine;<p>Create an user &OpenCurlyDoubleQuote;<b>dineshonjava<&sol;b>” in MongoDB database &OpenCurlyDoubleQuote;<b>dineshonjavaDB<&sol;b>”&period;<&sol;p>&NewLine;<pre class&equals;"highlight">&gt&semi; use dineshonjavaDB &NewLine;&gt&semi; db&period;addUser&lpar;"dineshonjava"&comma;"password"&rpar; &NewLine;<&sol;pre>&NewLine;<div class&equals;"separator" style&equals;"clear&colon; both&semi; text-align&colon; center&semi;"><img src&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;wp-content&sol;uploads&sol;2013&sol;01&sol;auth&period;png" border&equals;"0" &sol;><&sol;div>&NewLine;<p>To start mongoDB in secure mode&comma; just provide the <b>&&num;8220&semi;–auth&&num;8221&semi;<&sol;b> argument<&sol;p>&NewLine;<pre class&equals;"highlight">&gt&semi; mongod --auth &NewLine;<&sol;pre>&NewLine;<div id&equals;"ads-id" align&equals;"center"><&sol;div>&NewLine;<h2><b>2&period; Now&comma; the MongoDB is started in secure &sol;authentication mode &lpar;authenticate with username and password is require&rpar;&period;<&sol;b><&sol;h2>&NewLine;<p>if you try to access the auth db then we will get following&period;<&sol;p>&NewLine;<pre class&equals;"highlight">&gt&semi; db&period;auth&lpar;"dineshonjava"&comma;"password"&rpar; &NewLine;1 &NewLine;&gt&semi; db&period;auth&lpar;"dineshonjava"&comma;"password1"&rpar; &NewLine;Error&colon; &lbrace; errmsg&colon; "auth fails"&comma; ok&colon; 0&period;0 &rcub; &NewLine;0 &NewLine;&gt&semi; &NewLine;<&sol;pre>&NewLine;<div class&equals;"separator" style&equals;"clear&colon; both&semi; text-align&colon; center&semi;"><img src&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;wp-content&sol;uploads&sol;2013&sol;01&sol;auth1&period;png" border&equals;"0" &sol;><&sol;div>&NewLine;<h2><b>3&period; Java connect MongoDB<&sol;b><&sol;h2>&NewLine;<p>In Java&comma; you can use &&num;8220&semi;<b>db&period;authenticate<&sol;b>&&num;8221&semi; to handle the MongoDB authentication&period;<&sol;p>&NewLine;<pre class&equals;"highlight">DB db &equals; mongo&period;getDB&lpar;"dineshonjavaDB"&rpar;&semi; &NewLine;boolean auth &equals; db&period;authenticate&lpar;"dineshonjava"&comma; "password"&period;toCharArray&lpar;&rpar;&rpar;&semi; &NewLine;<&sol;pre>&NewLine;<p>If username and password is valid&comma; &&num;8220&semi;auth&&num;8221&semi; will be true&comma; else it will be false and return the following error pattern<&sol;p>&NewLine;<pre class&equals;"highlight">com&period;mongodb&period;MongoException&colon; unauthorized db&colon;dineshonjavaDB lock type&colon;-1 client&colon;192&period;168&period;1&period;3 &NewLine; at com&period;mongodb&period;MongoException&period;parse&lpar;MongoException&period;java&colon;82&rpar; &NewLine; at com&period;mongodb&period;DBApiLayer&dollar;MyCollection&period;&lowbar;&lowbar;find&lpar;DBApiLayer&period;java&colon;302&rpar; &NewLine; at com&period;mongodb&period;DBCursor&period;&lowbar;check&lpar;DBCursor&period;java&colon;354&rpar; &NewLine; at com&period;mongodb&period;DBCursor&period;&lowbar;hasNext&lpar;DBCursor&period;java&colon;484&rpar; &NewLine; at com&period;mongodb&period;DBCursor&period;hasNext&lpar;DBCursor&period;java&colon;509&rpar; &NewLine; at com&period;dineshonjava&period;mongo&period;test&period;MongoAuthDemo&period;main&lpar;MongoAuthDemo&period;java&colon;24&rpar; &NewLine; &NewLine;<&sol;pre>&NewLine;<p><b>See the full example as follows&period;<&sol;b><&sol;p>&NewLine;<pre class&equals;"highlight">package com&period;dineshonjava&period;mongo&period;test&semi; &NewLine; &NewLine;import java&period;net&period;UnknownHostException&semi; &NewLine; &NewLine;import com&period;mongodb&period;DB&semi; &NewLine;import com&period;mongodb&period;DBCollection&semi; &NewLine;import com&period;mongodb&period;Mongo&semi; &NewLine;import com&period;mongodb&period;MongoException&semi; &NewLine; &NewLine;&sol;&ast;&ast; &NewLine; &ast; &commat;author Dinesh Rajput &NewLine; &ast; &NewLine; &ast;&sol; &NewLine;public class MongoAuthDemo &lbrace; &NewLine; &NewLine; public static void main&lpar;String&lbrack;&rsqb; args&rpar; &lbrace; &NewLine; &NewLine; try &lbrace; &NewLine; &NewLine; Mongo mongo &equals; new Mongo&lpar;"localhost"&comma; 27017&rpar;&semi; &NewLine; DB db &equals; mongo&period;getDB&lpar;"dineshonjavaDB"&rpar;&semi; &NewLine; boolean auth &equals; db&period;authenticate&lpar;"dineshonjava"&comma; "password"&period;toCharArray&lpar;&rpar;&rpar;&semi; &NewLine; DBCollection collection &equals; db&period;getCollection&lpar;"empCollection"&rpar;&semi; &NewLine; if&lpar;auth&rpar;&lbrace; &NewLine; System&period;out&period;println&lpar;"TRUE"&rpar;&semi; &NewLine; &rcub;else&lbrace; &NewLine; System&period;out&period;println&lpar;"FALSE"&rpar;&semi; &NewLine; &rcub; &NewLine; &NewLine; System&period;out&period;println&lpar;"Done"&rpar;&semi; &NewLine; &NewLine; &rcub; catch &lpar;UnknownHostException e&rpar; &lbrace; &NewLine; e&period;printStackTrace&lpar;&rpar;&semi; &NewLine; &rcub; catch &lpar;MongoException e&rpar; &lbrace; &NewLine; e&period;printStackTrace&lpar;&rpar;&semi; &NewLine; &rcub; &NewLine; &NewLine; &rcub; &NewLine; &NewLine;&rcub; &NewLine;<&sol;pre>&NewLine;<p>If everything is fine then we will get the following output-<&sol;p>&NewLine;<div style&equals;"background-color&colon; &num;ff99cc&semi;"><b>output-<&sol;b><br &sol;>&NewLine;TRUE<br &sol;>&NewLine;Done<&sol;div>&NewLine;<h2><b>Download Source Code &plus; Libs<&sol;b><br &sol;>&NewLine;<a href&equals;"https&colon;&sol;&sol;sites&period;google&period;com&sol;site&sol;dinesh9582486434&sol;my-forms&sol;MongoDBAuthDemo&period;zip&quest;attredirects&equals;0&amp&semi;d&equals;1" target&equals;"&lowbar;blank" rel&equals;"noopener"><b>MongoDBAuthDemo&period;zip<&sol;b><&sol;a><&sol;h2>&NewLine;<p><b>References<&sol;b><br &sol;>&NewLine;<a href&equals;"http&colon;&sol;&sol;www&period;mongodb&period;org&sol;display&sol;DOCS&sol;Java&plus;Tutorial&num;JavaTutorial-Authentication&percnt;28Optional&percnt;29" target&equals;"&lowbar;blank" rel&equals;"noopener"><b>MongoDB Java Authentication<&sol;b><&sol;a><br &sol;>&NewLine;<a href&equals;"http&colon;&sol;&sol;www&period;mongodb&period;org&sol;display&sol;DOCS&sol;Security&plus;and&plus;Authentication" target&equals;"&lowbar;blank" rel&equals;"noopener"><b>MongoDB Security and Authentication<&sol;b><&sol;a><&sol;p>&NewLine;<div style&equals;"background-color&colon; &num;ff99cc&semi;">                        <b>     &lt&semi;&lt&semi;<a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;java-mongodb-convert-json-data-to&sol;">previous<&sol;a>&lt&semi;&lt&semi;             &vert;&vert; <a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;introduction-to-mongodb&sol;">index  <&sol;a>&vert;&vert;         &gt&semi;&gt&semi;<a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;spring-data-mongodb-examples&sol;">next<&sol;a>&gt&semi;&gt&semi;<&sol;b><&sol;div>&NewLine;<p>&nbsp&semi;<&sol;p>&NewLine;<div class&equals;"wp-post-navigation"> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <div class&equals;"wp-post-navigation-pre"> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;spring-data-mongodb-examples&sol;">Previous<&sol;a> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <&sol;div> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <div class&equals;"wp-post-navigation-next"> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <a href&equals;"https&colon;&sol;&sol;dineshonjava&period;com&sol;spring-data-mongodb-hello-world-example&sol;">Next<&sol;a> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab; <&sol;div> &NewLine;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;&Tab;<&sol;div>&NewLine;<script type&equals;"text&sol;javascript">&NewLine;jQuery&lpar;document&rpar;&period;ready&lpar;function&lpar;&dollar;&rpar; &lbrace;&NewLine; &dollar;&period;post&lpar;'https&colon;&sol;&sol;dineshonjava&period;com&sol;wp-admin&sol;admin-ajax&period;php'&comma; &lbrace;action&colon; 'mts&lowbar;view&lowbar;count'&comma; id&colon; '585'&rcub;&rpar;&semi;&NewLine;&rcub;&rpar;&semi;&NewLine;<&sol;script>

Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

4 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

4 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

4 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

4 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

4 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

4 years ago