使用rmongodb连接本地MongoDB时认证失败问题求助
Hey there, let's figure out why your rmongodb connection to MongoDB is throwing that Authentication failed error. I've dealt with similar issues on Ubuntu 16.04 with MongoDB 3.2 before, so here are the steps to troubleshoot and fix this:
Verify your MongoDB user setup is correct
MongoDB 3.2 requires administrative users to be created in theadmindatabase with appropriate roles. First, log into your MongoDB shell to check or recreate the user:mongo use admin # Check if the user exists db.getUser("admin") # If it doesn't exist or has wrong roles, recreate it db.dropUser("admin") # Skip if the user doesn't exist db.createUser({ user: "admin", pwd: "admin123", roles: ["root"] # Root role gives full access, adjust if needed })Make sure you run these commands in the
admindatabase, as that's where MongoDB stores administrative credentials.Ensure MongoDB is configured to enforce authentication
Open your MongoDB config file (usually at/etc/mongod.conf) and check that the security section has authorization enabled:security: authorization: enabledSave the file and restart the MongoDB service to apply changes:
sudo service mongod restart # Ubuntu 16.04 uses this instead of systemctl for some setupsExplicitly specify the authentication mechanism in rmongodb
Older versions of rmongodb might not default to the correct authentication mechanism for MongoDB 3.2 (which uses SCRAM-SHA-1 by default). Try adding theauthenticationMechanismparameter to your connection code:mongo <- mongo.create( host='127.0.0.1', username = "admin", password = "admin123", db = "admin", authenticationMechanism = "SCRAM-SHA-1" )Try manual authentication after creating a basic connection
Sometimes the combinedmongo.createcall can have hidden issues. Test creating an unauthenticated connection first, then authenticate separately:# Create basic connection mongo <- mongo.create(host='127.0.0.1') # Manually authenticate auth_result <- mongo.authenticate(mongo, username = "admin", password = "admin123", db = "admin") # Check if authentication succeeded print(auth_result)If this works, you know the issue was with the combined connection parameters rather than the credentials themselves.
Double-check port and local connectivity
While you're connecting to127.0.0.1, confirm MongoDB is listening on the default port 27017:netstat -tulpn | grep mongodYou should see a line showing
mongodlistening on127.0.0.1:27017. If not, your MongoDB service might not be running correctly—restart it and check the logs (/var/log/mongodb/mongod.log) for errors.
内容的提问来源于stack exchange,提问作者Kavita Madiwal

