Categories: MongoDB

Authentication to MongoDB with Java

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:

MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("test");
boolean auth = db.authenticate(myUserName, myPassword);

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.

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.

1. Start MongoDB in Secure Mode

Create an user “dineshonjava” in MongoDB database “dineshonjavaDB”.

> use dineshonjavaDB
> db.addUser("dineshonjava","password")

To start mongoDB in secure mode, just provide the “–auth” argument

> mongod --auth

2. Now, the MongoDB is started in secure /authentication mode (authenticate with username and password is require).

if you try to access the auth db then we will get following.

> db.auth("dineshonjava","password")
1
> db.auth("dineshonjava","password1")
Error: { errmsg: "auth fails", ok: 0.0 }
0
>

3. Java connect MongoDB

In Java, you can use “db.authenticate” to handle the MongoDB authentication.

DB db = mongo.getDB("dineshonjavaDB");
boolean auth = db.authenticate("dineshonjava", "password".toCharArray());

If username and password is valid, “auth” will be true, else it will be false and return the following error pattern

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)

See the full example as follows.

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();
  }
 
 }

}

If everything is fine then we will get the following output-

output-
TRUE
Done

Download Source Code + Libs
MongoDBAuthDemo.zip

References
MongoDB Java Authentication
MongoDB Security and Authentication

                             <<previous<<             || index  ||         >>next>>

 

Previous
Next
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…

2 years ago

Decorator Pattern using Lambda

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

2 years ago

Delegating pattern using lambda

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

2 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;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

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

2 years ago

Scheduler @Scheduled Annotation Spring Boot

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

3 years ago