I want to login only by using x509 authentication in mongodb

27 Views Asked by At

Entries from my config file:

net:
  port: 27017
  bindIp: 127.0.0.1
  tls:
      mode: requireTLS
      certificateKeyFile: D:\certnew\MongoDb\Test3\test-server.pem
      CAFile: D:\certnew\MongoDb\Test3\test-ca.pem

security:
  authorization: enabled
  clusterAuthMode: x509

Trying to connect with server Certificate:

mongosh --tls --tlsCertificateKeyFile D:\certnew\MongoDb\Test3\test-server.pem --tlsCAFile D:\certnew\MongoDb\Test3\test-ca.pem

Trying to connect with Client Certificate:

mongosh --tls --tlsCertificateKeyFile D:\certnew\MongoDb\Test3\test-client.pem --tlsCAFile D:\certnew\MongoDb\Test3\test-ca.pem

Trying to connect with x509 Auth:

mongosh --tls --tlsCertificateKeyFile D:\certnew\MongoDb\Test3\test-client.pem --tlsCAFile D:\certnew\MongoDb\Test3\test-ca.pem --authenticationDatabase '$external' --authenticationMechanism MONGODB-X509

I am able to connect in all these above mentioned methods but I want only x509 authentication and other methods should not be allowed.

1

There are 1 best solutions below

0
Wernfried Domscheit On

You must distinct between connecting and authentication to your MongoDB.

Your first and second command only connects to your MongoDB, but you are not authenticated. If you try to run a command, then you will get a "not authenticated" error. You can only run commands like db.help(), db.listCommands() or of course db.auth(username, password) to authenticate on the current connection.

You can check current authentication with

test> db.runCommand({ connectionStatus: 1 })
{
  authInfo: { authenticatedUsers: [], authenticatedUserRoles: [] },
  ok: 1
}

The third command connects and authenticates to your database.

Note, I assume you are running a stand-alone MongoDB, not a Replica Set or Sharded Cluster. In this case security.clusterAuthMode: x509 has no effect, you can skip it.

You can enforce a client certificate with this setting:

net:
  tls:
    mode: requireTLS
    certificateKeyFile: D:\certnew\MongoDb\Test3\test-server.pem
    CAFile: D:\certnew\MongoDb\Test3\client-ca.pem
    allowConnectionsWithoutCertificates: false

A connection without certificate will be rejected:

mongosh --tls --tlsCAFile server-ca.pem
MongoServerSelectionError: connection <monitor> to 127.0.0.1:27017 closed