How to change my mongoDB user password as non administrator? - mongodb

I understand I can change a user's password by running db.changeUserPassword() as an MongoDB administrator. However, as a user with no administrator privilege, can I change my password just with my own account?
Thanks,
Although solution provided by Gergo worked. But I had to create a new role in order for it to work. I thought changeOwnPassword should be a built in privilege and not require additional admin work. Creating a dedicated role just for the purpose to be able to change user's own password is overkill in MongoDB.

If you have the necessary privileges, you can change your own password. You can verify that you have the necessary privileges by running this command:
db.runCommand(
{
usersInfo:"username",
showPrivileges:true
}
)
If it contains changeOwnPassword, then you can change the password:
db.runCommand(
{ updateUser: "username",
pwd: "password"
}
)
You can find more information in the MongoDB documentation.

In the admin database, create a new role with changeOwnPassword action.
use admin
db.createRole(
{ role: "changeOwnPasswordRole",
privileges: [
{
resource: { db: "", collection: ""},
actions: [ "changeOwnPassword" ]
}
],
roles: []
}
)
create a new user with changeOwnPasswordRole role and along with other roles
use test
db.createUser(
{
user:"user123",
pwd:"12345678",
roles:[ "readWrite", { role:"changeOwnPasswordRole", db:"admin" } ]
}
)
login the above user credentials
Use the below command to update own password
db.updateUser("user123",{pwd: "pass123"})

Related

Get List of User with Permission

I want to create a query which basically finds out the users with their privileges i.e if a user has a role - admin then want to see what privileges have this role and to whom this role is assigned
Use db.getUsers() command:
db.getUsers({ showCredentials: true })
Note, users are defined on a database, typically admin. So you would have to run
db.getSiblingDB("admin").getUsers({ showCredentials: true })
In case you need to scan all databases, you could use this one:
db.adminCommand({ listDatabases: 1, nameOnly: true }).databases.forEach(function (doc) {
db.getSiblingDB(doc.name).getUsers({ showCredentials: true }).forEach(function (user) {
printjson({ _id: user._id, user: user.user, db: user.db, roles: user.roles });
});
});
The privileges of a role you can get with db.getRoles(). Similar to db.getUsers() the roles could be defined in any database.
In general I don't see any reason to define users and roles in other database than admin - it makes your life much easier.

how to make mongo-express show all db?

here is my mongo-express config, when i login http://192.168.1.104:8081, it only shows the admin db, i want it to show all db. i had ran this command before
use admin
db.createUser(
{
user: "root",
pwd: "password",
roles: [ "root" ]
}
)
config file:
'use strict';
var url = require('url');
if (typeof process.env.MONGODB_PORT === 'string') {
var mongoConnection = url.parse(process.env.MONGODB_PORT);
process.env.ME_CONFIG_MONGODB_SERVER = mongoConnection.hostname;
process.env.ME_CONFIG_MONGODB_PORT = mongoConnection.port;
}
module.exports = {
mongodb: {
server: process.env.ME_CONFIG_MONGODB_SERVER || 'localhost',
port: process.env.ME_CONFIG_MONGODB_PORT || 27017,
//autoReconnect: automatically reconnect if connection is lost
autoReconnect: true,
//poolSize: size of connection pool (number of connections to use)
poolSize: 4,
//set admin to true if you want to turn on admin features
//if admin is true, the auth list below will be ignored
//if admin is true, you will need to enter an admin username/password below (if it is needed)
admin: true,
// >>>> If you are using regular accounts, fill out auth details in the section below
// >>>> If you have admin auth, leave this section empty and skip to the next section
auth: [
/*
* Add the the name, the username, and the password of the databases you want to connect to
* Add as many databases as you want!
{
database: 'test',
username: 'user',
password: 'pass'
}
*/
],
// >>>> If you are using an admin mongodb account, or no admin account exists, fill out section below
// >>>> Using an admin account allows you to view and edit all databases, and view stats
//leave username and password empty if no admin account exists
adminUsername: process.env.ME_CONFIG_MONGODB_ADMINUSERNAME || '',
adminPassword: process.env.ME_CONFIG_MONGODB_ADMINPASSWORD || '',
//whitelist: hide all databases except the ones in this list (empty list for no whitelist)
whitelist: [],
//blacklist: hide databases listed in the blacklist (empty list for no blacklist)
blacklist: []
},
site: {
host: '192.168.1.104',
port: 8081,
cookieSecret: process.env.ME_CONFIG_SITE_COOKIESECRET || 'cookiesecret',
sessionSecret: process.env.ME_CONFIG_SITE_SESSIONSECRET || 'sessionsecret',
cookieKeyName: 'mongo-express',
sslEnabled: process.env.ME_CONFIG_SITE_SSL_ENABLED || false,
sslCert: process.env.ME_CONFIG_SITE_SSL_CRT_PATH || '',
sslKey: process.env.ME_CONFIG_SITE_SSL_KEY_PATH || ''
},
//set useBasicAuth to true if you want to authehticate mongo-express loggins
//if admin is false, the basicAuthInfo list below will be ignored
//this will be true unless ME_CONFIG_BASICAUTH_USERNAME is set and is the empty string
useBasicAuth: process.env.ME_CONFIG_BASICAUTH_USERNAME !== '',
basicAuth: {
username: process.env.ME_CONFIG_BASICAUTH_USERNAME || 'root',
password: process.env.ME_CONFIG_BASICAUTH_PASSWORD || 'password'
},
options: {
//documentsPerPage: how many documents you want to see at once in collection view
documentsPerPage: 10,
//editorTheme: Name of the theme you want to use for displaying documents
//See http://codemirror.net/demo/theme.html for all examples
editorTheme: process.env.ME_CONFIG_OPTIONS_EDITORTHEME || 'rubyblue',
//The options below aren't being used yet
//cmdType: the type of command line you want mongo express to run
//values: eval, subprocess
// eval - uses db.eval. commands block, so only use this if you have to
// subprocess - spawns a mongo command line as a subprocess and pipes output to mongo express
cmdType: 'eval',
//subprocessTimeout: number of seconds of non-interaction before a subprocess is shut down
subprocessTimeout: 300,
//readOnly: if readOnly is true, components of writing are not visible.
readOnly: false
},
// Specify the default keyname that should be picked from a document to display in collections list.
// Keynames can be specified for every database and collection.
// If no keyname is specified, it defalts to '_id', which is a mandatory feild.
// For Example :
// defaultKeyNames{
// "world_db":{ //Database Name
// "continent":"cont_name", // collection:feild
// "country":"country_name",
// "city":"name"
// }
// }
defaultKeyNames: {
}
};
Remarks:
in above config,
basicAuth: {
username: process.env.ME_CONFIG_BASICAUTH_USERNAME || 'root',
password: process.env.ME_CONFIG_BASICAUTH_PASSWORD || 'password'
},
i changed the username, password to root and password repectively, when i access http://192.168.1.104:8081 , i need to enter root and password in http auth prompt so as i entering the mongo-express web panel.
This is my first answer on StackOverflow, but hopefully it's helpful.
Issue in your case seems to be database authentication defined in config.js.
You need to pass the db credentials through "auth" section and not through "basicAuth".
Also, once you correct the config.js file, start the mongo-express with -a switch, i.e. -> cd YOUR_PATH/node_modules/mongo-express/ && node app.js -a
Corrected section of config.js :
admin: true,
// >>>> If you are using regular accounts, fill out auth details in the section below
// >>>> If you have admin auth, leave this section empty and skip to the next section
auth: [
/*
* Add the the name, the username, and the password of the databases you want to connect to
* Add as many databases as you want!
{
database: 'test',
username: 'user',
password: 'pass'
}
*/
],
// >>>> If you are using an admin mongodb account, or no admin account exists, fill out section below
// >>>> Using an admin account allows you to view and edit all databases, and view stats
//leave username and password empty if no admin account exists
adminUsername: process.env.ME_CONFIG_MONGODB_ADMINUSERNAME || 'root',
adminPassword: process.env.ME_CONFIG_MONGODB_ADMINPASSWORD || 'password',

Authentication error (credentials missing in user document) in Mongo 3.0.1

I am having trouble with a basic user connection to my new Mongo setup.
The error looks like this in mongo.log:
authenticate db: a { authenticate: 1, user "u", nonce: "xxx", key: "xxx" }
Failed to authenticate u#a with mechanism MONGODB-CR:AuthenticationFailed MONGODB-CR credentials missing in user document
and here is my user setup
> use a
switched to db a
> show users
{
"_id":"a.u",
"user":"u",
"db":"a",
roles:[
{
"role":"readWrite",
"db":"a"
},
{
"role":"dbAdmin",
"db":"a"
}
]
}
Id user u has readWrite on database a, why is he being rejected? All the examples I found when googling where users that were created in the wrong db.
Thanks in advance.

MongoError: auth failed mongoose connection string

I can connect to the DB through terminal, but getting this error using mongoose and gulp.
mongoose/node_modules/mongodb/lib/mongodb/connection/base.js:246
MongoError: auth failed
My connection string is:
mongodb://usr:psw#localhost:27017/dbname
Any idea what it can be?
I installed MEAN from MEAN packaged by Bitnami for windows 7 using the following password: 123456
Syntax for connection string to connect to mongodb with mongoose module
mongoose.connect("mongodb://[usr]:[pwd]#localhost:[port]/[db]",{auth:{authdb:"admin"}});
If you don't have {auth:{authdb:"admin"}} in the connection string, you will get the following error: MongoError: Authentication failed.
JS Example: mongo-test/app.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://root:123456#localhost/test',{auth:{authdb:"admin"}});
mongoose.set('debug', true); // turn on debug
just add ?authSource=yourDB&w=1 to end of db url
mongoose.connect('mongodb://user:password#host/yourDB?authSource=yourDB&w=1')
this work for me . &w=1 is important
There is many ways to make it work. This is what worked for me [mongoose v5.9.15] :
mongoose.connect('mongodb://localhost:27017/', {
auth: {
user:'root',
password:'example'
},
authSource:"admin",
useUnifiedTopology: true,
useNewUrlParser: true
})
You might want to do something like this...
var opt = {
user: config.username,
pass: config.password,
auth: {
authdb: 'admin'
}
};
var connection = mongoose.createConnection(config.database.host, 'mydatabase', config.database.port, opt);
'authdb' option is the database you created the user under.
mongoose.connect("mongodb://[host]/[db]", { auth:{
authdb: "admin",
user: [username],
password: [pw]
}}).then(function(db){
// do whatever you want
mongoose.connection.close() // close db
})
Do you have a user set up for dbname? By default, no user is required to connect to the database unless you explicitly set one. If you haven't, you should just try to connect to mongodb://localhost:27017/dbname and see if you still get an error.
I have found the solution hier, looks like when you create an user from the mongo shell, it makes SCRAM-SHA-1 instead of MongoDB-CR. So the solution to create a new user with MongoDB-CR authentication.
MongoDB-CR Authentication failed
just make sure that your database is created.
and also if your user is not added in the admin database, then make sure to add it by putting
db.createUser(
... {user:'admin',pwd:'admin',roles:['root']}
... )
This worked for me for mongod --version = db version v3.6.13
mongoose.connect('mongodb://localhost/expressapi', {
auth: {
authdb: "admin",
user: "root",
password: "root",
}
});
mongo mongodb://usr:psw#localhost:27017/dbname
Password should be alphanumeric only
User should be also available in db 'dbname' (Note : Even if user is super admin)
With above changes it connected successfully.
mongoose.connect("mongodb://[usr]:[pwd]#localhost:[port]/[db]",{ authSource: 'admin', useNewUrlParser: true, useUnifiedTopology: true });
I was getting same error. Resolved by adding authSource option to connect function solved the issue. see above code.
The connection string will be like
mongodb://username:password#localhost:27017/yourdbname?authSource=admin

Authenticate in MongoDB

when setup mongodb, i has been created admin account:
use admin
db.createUser(
{
user: "demo",
pwd: "demo",
roles:
[
{
role: "userAdminAnyDatabase",
db: "admin"
}
]
}
)
but when connection database using java:
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("mydb");
String username = "demo";
String password = "demo";
boolean auth = db.authenticate(username, password.toCharArray());
System.out.println(auth);
result false, somebody can help me???
See the link for procedure of authentication done in mongodb Enable Client Authentication, may be you missed the first step, hope it helps you.