Mongo 3.6开启认证后执行命令提示not authorized问题排查
Let's walk through this issue step by step—this is a super common authentication gotcha with MongoDB 3.6, so we'll get you sorted out quickly.
admin Database MongoDB ties user credentials to the database where you create them, and the root role only grants full privileges when authenticated against the admin db. If you created your root user in another database (like test), it won't have the global access you expect.
Double-check you ran these commands when creating the root user:
use admin db.createUser( { user: "root", pwd: "yourRootPassword", roles: [ { role: "root", db: "admin" } ] } )
When logging in, you need to explicitly tell MongoDB to use the admin database for authentication. You can do this either during login:
mongo -u root -p yourRootPassword --authenticationDatabase admin
Or after connecting to the shell:
use admin db.auth("root", "yourRootPassword")
If you skip the --authenticationDatabase flag, MongoDB will try to authenticate against the default test database, which doesn't have your root user's credentials—hence the authorization error.
Make sure your mongod.conf (or mongodb.conf) has authorization turned on. Look for this section:
security: authorization: enabled
If this setting was missing or set to disabled earlier, even though you created users, MongoDB wasn't enforcing authentication. After updating the config, restart the mongod service for changes to take effect—this is easy to forget!
If your app user needs to list databases, you need to grant them the right privileges. For example, if your app uses a myapp database, create the user with both database-specific access and the listDatabases privilege:
use admin db.createUser( { user: "appUser", pwd: "appPassword", roles: [ { role: "readWrite", db: "myapp" }, { role: "listDatabases", db: "admin" } ] } )
If your app doesn't actually need to list all databases, just connect directly to your app's database instead of trying to run listDatabases—that's a better practice anyway.
When connecting via Node.js, your connection string must include the authSource parameter pointing to the admin database. Here's an example:
const MongoClient = require('mongodb').MongoClient; const uri = "mongodb://appUser:appPassword@localhost:27017/myapp?authSource=admin"; MongoClient.connect(uri, function(err, client) { if (err) throw err; // Your app logic here client.close(); });
Without authSource=admin, MongoDB will try to authenticate against the myapp database, which doesn't store your app user's credentials (since you created them in admin).
内容的提问来源于stack exchange,提问作者CodeChimp

