Solved

CData for MongoDB JDBC error Authentication failed

  • 19 October 2023
  • 5 replies
  • 93 views

Userlevel 3
Badge

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

icon

Best answer by Luçjano Capo 20 October 2023, 15:16

View original

5 replies

Userlevel 5
Badge +1

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.

Userlevel 7
Badge

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.

Userlevel 3
Badge

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 😪

 

Userlevel 3
Badge

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?

Userlevel 5
Badge +1

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