I have a database (use myDatabase) where I set a user (
db.createUser({user: "username", pwd: "password", roles: ["readWrite","dbAdmin"]})
I want authentication when “use myDatabase” command is used.
Also in app js:
mongoose.connect('mongodb://localhost:27017/myDatabase', {
useNewUrlParser: true,
useUnifiedTopology: true
});
This connects to db too without username and password.
I tried by changing mongod.cfg with
secutriy:
authorization: enabled
mongod --auth --port 27017 --dbpath /var/lib/myDatabase
from this tutorial Enable Access Control — MongoDB Manual
… but then it fails to connect to server.
Can you please advise how to set username and password requests for my database?
What error are you getting?
Can you connect from shell with new user id/PWD you created after enabling acces control?
Your connect string or app.js will change.Where have you defined user id & password in your file
Thanks for your reply.
- I stop MongoDB in Windows Services
- Change the mongod.cfg with security: authorization: enabled
After these, I cannot reconnect MongoDB in Windows Services.
In cmd:
mongod --auth --port 27017 --dbpath /var/lib/mongodb
and
mongo --port 27017 -u "myusername" --authenticationDatabase "admin" -p
result:
MongoDB shell version v4.4.3
Enter password:
connecting to: mongodb://127.0.0.1:27017/?authSource=admin&compressors=disabled&gssapiServiceName=mongodb
Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: No connection could be made because the target machine actively refused it. :
connect@src/mongo/shell/mongo.js:374:17
@(connect):2:6
exception: connect failed
exiting with code 1
You say you modified mongod.cfg but you are starting mongod from command line?
You have to check why your mongod did not start from service
Also donot run multiple mongods on same port
I would suggest not to disturb your default mongod running on port 27017 instead create another mongod with different dbpath,logpath,port etc and do your authentication exercise on it
1 Like
Somehow it is working partially.
With mongod.cfg authentication, mongodb service could be started in Windows Services.
In command line:
mongo --port 27017 -u "username" -p "password" --authenticationDatabase "admin"
result
MongoDB shell version v4.4.3
connecting to: mongodb://127.0.0.1:27017/?authSource=admin&compressors=disabled&gssapiServiceName=mongodb
Error: Authentication failed. :
connect@src/mongo/shell/mongo.js:374:17
@(connect):2:6
exception: connect failed
exiting with code 1
In app js
mongoose.connect('mongodb://username:password@localhost:27017/myDatabase
Database can be reached.
It is working now fully,
In command line I just wrote mongo
and use myDatabase
then db.auth("username","password")
gave me access to data
2 Likes