IceRevenge
IceRevenge

Reputation: 1583

Mongoose: authenticate onto different Mongo-databases with admin-priviliges of one user

I have a server on which I am running a MongoDB. I set it up with an admin database and a user that has read-write-priviliges for all databases (readWriteAnyDatabase). Additionally, I enabled authorization to be necessary in the mongod.conf (security: authorization: "enabled"). The server also has ssh.

Now I am trying to access that database from my laptop using mongoose and tunnel-ssh:

const mongoose = require("mongoose");
const fs = require("fs/promises");
const tunnel = require("tunnel-ssh");

const sshConfig = {
  username: "<USERNAME_ON_SERVER>",
  host: "<IP_ADDRESS>",
  agent: "pageant",
  privateKey: await fs.readFile("C:\\Users\\<USER_NAME>\\.ssh\\id_rsa"),
  port: 22,
  dstPort: 27017,
  passphrase: "<SSH-PASSPHRASE>"
};

let sshConnection;
try {
  sshConnection = await new Promise((resolve, reject) => tunnel(sshConfig, (error, server) => {
  if (error)
    reject(error);
  else
    resolve(server);
  }));
} catch (err) {
  console.log("SSH connection error:", err);
}

const mongoDB = mongoose.createConnection("mongo://adminName:adminPassword@localhost:27017/admin?retryWrites=true&w=majority", { 
  useUnifiedTopology: true, 
  useNewUrlParser: true ,
  useFindAndModify: false,
  useCreateIndex: true 
});

try {
  await new Promise(resolve => mongoDB.once("open", resolve));
} catch (err) {
  console.error("Error while connecting to mongoDB", err);
}

mongoDB.on("error", error => console.error("MongoDB-Error", error));

Connecting to this first admin database works fine. I can read and write to this database with my models.

My question is if it is possible to create other new databases in mongoose.

If I try to replace /admin in the URI to the database with a new name I get an authentification error.

I am aware that I could create and grant access to the databases in before-hand on the server but I would rather be able to add new databases per code.

Lastly, I thought of the option of disabling the authorization on the server so that I can access all of the databases without the need of an user. As I still have the ssh-encryption is the user-password-authentication actually necessary?

Upvotes: 0

Views: 234

Answers (1)

Joe
Joe

Reputation: 28336

If the user was created in the admin database, but you want to connect to a different database using the URI, you will need to specify authSource in the URI so the right user account can be found.

"mongo://adminName:adminPassword@localhost:27017/otherdb?authSource=admin&retryWrites=true&w=majority"

Upvotes: 2

Related Questions