如何为MongoDB启用认证并解决与Spring Boot连接被拒问题?
Hey there! Let's walk through solving your connection issue and getting your authenticated MongoDB setup working properly—since you're new to this, I'll break it down step by step.
First: Diagnose the "Connection Refused" Error
You mentioned MongoDB is running, but your Spring app can't connect. Let's rule out the basics first:
Check if MongoDB is listening on port 27017
Run this command on your MongoDB server to verify:# On Linux/macOS ss -tulpn | grep mongod # On Windows (Command Prompt) netstat -ano | findstr :27017If you don't see
mongodlisted against port 27017, double-check that MongoDB actually started successfully (check logs withsudo journalctl -u mongodon Linux).Verify your host and firewall settings
- Make sure the
<host name>in your Spring config is correct: if your app is on the same server as MongoDB, uselocalhostor127.0.0.1. If it's on another server, use the MongoDB server's public/private IP. - Ensure your server's firewall (or cloud security group) allows incoming traffic on port 27017 from your app's IP address. Don't open it to everyone unless absolutely necessary!
- Make sure the
Check MongoDB's bindIp configuration
Open your MongoDB config file (usually/etc/mongod.confon Linux,mongod.cfgon Windows) and look for thenetsection:net: port: 27017 bindIp: 127.0.0.1 # Default is local-onlyIf your app is on a different server, change
bindIpto0.0.0.0(allows all IPs, not ideal for production) or your app server's specific IP. Restart MongoDB after making changes:sudo systemctl restart mongod # Linux # Windows: Restart the MongoDB service via Services.msc
Next: Enable Authentication in MongoDB
Now let's set up the authenticated user and database your app needs:
Log into the MongoDB shell
Run this on your MongoDB server:mongosh # Use `mongo` for older MongoDB versionsCreate an admin user
Switch to theadmindatabase (where MongoDB stores user credentials) and create a user with admin privileges:use admin db.createUser({ user: "admin_user", pwd: "YourStrongAdminPassword123!", # Use a secure password roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ] })Enable authentication in MongoDB config
Go back to yourmongod.conffile, find thesecuritysection, and add:security: authorization: enabledRestart MongoDB again to apply this change.
Create Your App's Database & Restricted User
Now let's make a dedicated user for your Spring app with access only to your test database:
Log into MongoDB with the admin user
mongosh -u admin_user -p YourStrongAdminPassword123! --authenticationDatabase adminCreate the app database and user
Switch to yourtestdatabase (it will be created automatically if it doesn't exist) and create a user with read/write access:use test db.createUser({ user: "app_user", pwd: "YourAppUserPassword456!", # Secure password for your app roles: [{ role: "readWrite", db: "test" }] })
Update Your Spring Configuration
Finally, update your Spring config to include the authentication details—this is what was missing before! Here's the corrected YAML:
spring: data: mongodb: port: 27017 host: <your-server-host> # Replace with your actual host/IP database: test username: app_user password: YourAppUserPassword456! authentication-database: admin
Test the Connection
Before firing up your Spring app, test the connection directly from your app server using the MongoDB shell:
mongosh mongodb://app_user:YourAppUserPassword456!@<your-server-host>:27017/test?authSource=admin
If you can connect successfully, your MongoDB setup is good to go—your Spring app should now connect without issues.
内容的提问来源于stack exchange,提问作者cszoltan422

