Skip to main content

I’ve downloaded JDBC driver for MongoDB but when using it with the correct username password, it throws the error:

Exception in thread "main" java.sql.SQLException: Failed to authenticate database 'testdb', Error code: :18] - "Authentication failed."..

 

        Class.forName("cdata.jdbc.mongodb.MongoDBDriver");
Properties prop = new Properties();
prop.setProperty("Server","127.0.0.1");
prop.setProperty("Port","27017");
prop.setProperty("Database","testdb");
prop.setProperty("User","useradmin");
prop.setProperty("Password","welcome!");
Connection conn = DriverManager.getConnection("jdbc:mongodb:", prop);
Statement stat = conn.createStatement();
boolean ret = stat.execute("SELECT name FROM users");

 

It throws error on the last line. These username password are correct and can be used in mongosh inside mongo server container

Hi @quangdutran809 

Thanks for reaching out on CData Community!

By looking at your issue, I can think of two areas to investigate:

1.) Check if the User - ‘useradmin’ is created under Database - ‘testdb’ and has access to the database. Mostly, the users created under ‘admin’ database face such issues.

2.) Check again if the credentials are correct, you are using right cases, and there are no whitespaces.


Hi @quangdutran809,

One thing that I wanted to add is the utilization of AuthDatabase connection property. I was able to replicate the same issue as you, but after setting this property, I was able to get data from mongoDB.

I would also recommend you specify the AuthScheme as well.

Give this method a try and let me know how it goes.


Thanks @Ankit Singh I think the user that I am using is the root user, which should have permissions on all db, this is how I set up that user in Docker:

FROM mongo:7.0.2
ENV MONGO_INITDB_ROOT_USERNAME adminuser
ENV MONGO_INITDB_ROOT_PASSWORD welcome!
ENV MONGO_INITDB_DATABASE testdb

Also, using MongoDB Compass with that user, I can browse dbtest normally.

Thanks @Luçjano Capo, seem legit but I’ve added both `AuthScheme` and `AuthDatabase` but it still gives the same error 😪

 


Ah I’ve just realized that I’ve use the wrong username but adding `AuthDatabase` really solves the issue. Thanks guys, maybe this should be added to the document?


Hi @quangdutran809
I think it is part of the documentation here: https://cdn.cdata.com/help/DGJ/jdbc/pg_connectionj.htm#authenticating-mongodb-connections. Since there are different Auth Schemes, it can be a bit confusing.


Reply