MogoDB driver connection to MongoDB Atlas with X509 certificate doesn't work

Hi there.

I’m stuck at connecting to MongoDB Atlas with X509 auth mechanism and a certificate.

We are running an MongoDB v6 Atlas cluster and I try to connect with the mongodb_driver (0.9.2) package.

I try to authenticate via X509 by providing a .pem certificate.

The config looks like this:

config :myapp, :mongo_config,
  name: :myapp,
  appname: "myapp",
  url: "mongodb+srv://",
  username: "myuser",
  auth_mechanism: :x509,
  ssl: true,
  ssl_opts: [
    certfile: Path.join([cert_dir, "mycert.pem"])

And I start it with

{Mongo, Application.fetch_env!(:myapp, :mongo_config)}

in my application.ex start function.

If I try a simple ping in an iex session, it works:


   "$clusterTime" => %{
     "clusterTime" => #BSON.Timestamp<1665059449:1>,
     "signature" => %{
       "hash" => #BSON.Binary<aca626330d4014449835f347178287ec49985029>,
       "keyId" => 7148690837596012550
   "ok" => 1.0,
   "operationTime" => #BSON.Timestamp<1665059449:1>

But if I try to list the collections, it fails:

iex> Mongo.show_collections(:myapp)

  enum: {:error,
     code: 13,
     error_labels: [],
     fail_command: false,
     host: nil,
     message: "command listCollections requires authentication",
     not_writable_primary_or_recovering: false,
     resumable: false,
     retryable_reads: false,
     retryable_writes: false
  funs: [#Function<39.108234003/1 in Stream.filter/2>,
   #Function<47.108234003/1 in>]

The user has readWrite@db rights, which should be enough.

I’m not sure if I correctly pass the certfile into the right config or if I need to do anything else.

To be sure that I can reach the MongoDB Atlas cluster I temporarily created a user with a password and tried to connect to the cluster by only providing the url mongodb+srv:// in the config which works and I got the collections available in these database.

Also, trying both auth mechanisms in MongoDB Compass works without problems.

So I think it is something with the config I constructed with the X509 auth mechanism and the certificate file.
But I can’t figure out what I do wrong.

Did someone of you know what I do wrong?


Did you follow the instructions described here:

As you can see, there are a lot of steps to be done and each step can fail, so it is hard to guess what is going wrong.

Try to use the mongosh with your configuration. If this is working, then go to check the configuration of the driver.


Yes, I tried basically everything left and right, mongosh, compass, golang and all works.

But I found out what I did wrong with my config and now have it working with the certificate.

First, the username needs to be the certificate subject.
This is different than the other methods I tried. They’re probably doing some magic behind the scenes.

And I need to set a password, even if there is none needed.

After that, the authentication with the certificate works.


1 Like