[{"data":1,"prerenderedAt":375},["ShallowReactive",2],{"blog-how-to/mongodb-auth":3},{"id":4,"title":5,"body":6,"category":356,"date":357,"dateModified":357,"description":358,"draft":359,"extension":360,"faq":361,"featured":359,"headerVariant":362,"image":361,"keywords":361,"meta":363,"navigation":364,"ogDescription":365,"ogTitle":361,"path":366,"readTime":361,"schemaOrg":367,"schemaType":368,"seo":369,"sitemap":370,"stem":371,"tags":372,"twitterCard":373,"__hash__":374},"blog/blog/how-to/mongodb-auth.md","How to Set Up MongoDB Authentication",{"type":7,"value":8,"toc":341},"minimark",[9,13,17,21,27,30,43,48,51,54,58,84,100,125,141,157,173,199,203,231,237,241,246,249,253,256,260,267,271,274,304,323],[10,11],"category-badge",{"category":12},"How-To Guide",[14,15,5],"h1",{"id":16},"how-to-set-up-mongodb-authentication",[18,19,20],"p",{},"Secure your MongoDB database with proper user authentication",[22,23,24],"tldr",{},[18,25,26],{},"TL;DR (20 minutes):\nStart MongoDB without auth, create an admin user, enable\nauthorization: enabled\nin mongod.conf, restart MongoDB, then create application-specific users with minimal required roles. Always use authenticated connection strings in your app.",[18,28,29],{},"Prerequisites:",[31,32,33,37,40],"ul",{},[34,35,36],"li",{},"MongoDB installed (local or server)",[34,38,39],{},"MongoDB shell access (mongosh)",[34,41,42],{},"Admin/root access to the server",[44,45,47],"h2",{"id":46},"why-this-matters","Why This Matters",[18,49,50],{},"A MongoDB instance without authentication is completely open to anyone who can connect to it. Thousands of MongoDB databases have been ransomed because they were left exposed on the internet without auth. In 2023 alone, over 30,000 unsecured MongoDB instances were found publicly accessible.",[18,52,53],{},"Setting up proper authentication prevents unauthorized access, enables audit logging, and is required for any compliance framework.",[44,55,57],{"id":56},"step-by-step-guide","Step-by-Step Guide",[59,60,62,67,70,81],"step",{"number":61},"1",[63,64,66],"h3",{"id":65},"connect-to-mongodb-without-auth-initial-setup","Connect to MongoDB without auth (initial setup)",[18,68,69],{},"If authentication isn't enabled yet, connect to create the first admin user:",[71,72,77],"pre",{"className":73,"code":75,"language":76},[74],"language-text","# Connect to MongoDB\nmongosh\n\n# Or with older mongo shell\nmongo\n","text",[78,79,75],"code",{"__ignoreMap":80},"",[18,82,83],{},"If MongoDB Atlas, skip to step 4 - Atlas handles this automatically.",[59,85,87,91,94],{"number":86},"2",[63,88,90],{"id":89},"create-an-admin-user","Create an admin user",[18,92,93],{},"In the admin database, create a user with full privileges:",[71,95,98],{"className":96,"code":97,"language":76},[74],"// Switch to admin database\nuse admin\n\n// Create admin user\ndb.createUser({\n  user: \"adminUser\",\n  pwd: passwordPrompt(),  // Prompts for password (more secure)\n  roles: [\n    { role: \"userAdminAnyDatabase\", db: \"admin\" },\n    { role: \"readWriteAnyDatabase\", db: \"admin\" },\n    { role: \"dbAdminAnyDatabase\", db: \"admin\" },\n    { role: \"clusterAdmin\", db: \"admin\" }\n  ]\n})\n\n// Or with explicit password (less secure, avoid in scripts)\ndb.createUser({\n  user: \"adminUser\",\n  pwd: \"yourStrongPassword123!\",\n  roles: [\"root\"]\n})\n",[78,99,97],{"__ignoreMap":80},[59,101,103,107,110,116,119],{"number":102},"3",[63,104,106],{"id":105},"enable-authentication-in-mongodb-config","Enable authentication in MongoDB config",[18,108,109],{},"Edit the MongoDB configuration file:",[71,111,114],{"className":112,"code":113,"language":76},[74],"# Location varies by OS:\n# Linux: /etc/mongod.conf\n# macOS (Homebrew): /usr/local/etc/mongod.conf\n# Windows: C:\\Program Files\\MongoDB\\Server\\{version}\\bin\\mongod.cfg\n\n# Add or modify security section:\nsecurity:\n  authorization: enabled\n",[78,115,113],{"__ignoreMap":80},[18,117,118],{},"Restart MongoDB:",[71,120,123],{"className":121,"code":122,"language":76},[74],"# Linux\nsudo systemctl restart mongod\n\n# macOS\nbrew services restart mongodb-community\n\n# Windows\nnet stop MongoDB && net start MongoDB\n",[78,124,122],{"__ignoreMap":80},[59,126,128,132,135],{"number":127},"4",[63,129,131],{"id":130},"create-application-specific-users","Create application-specific users",[18,133,134],{},"Connect as admin and create a user for your application:",[71,136,139],{"className":137,"code":138,"language":76},[74],"# Connect with admin credentials\nmongosh -u adminUser -p --authenticationDatabase admin\n\n# In the shell:\nuse myappdb\n\n// Create app user with minimal permissions\ndb.createUser({\n  user: \"myapp\",\n  pwd: passwordPrompt(),\n  roles: [\n    { role: \"readWrite\", db: \"myappdb\" }\n  ]\n})\n\n// For read-only access (reporting, analytics)\ndb.createUser({\n  user: \"myapp_readonly\",\n  pwd: passwordPrompt(),\n  roles: [\n    { role: \"read\", db: \"myappdb\" }\n  ]\n})\n",[78,140,138],{"__ignoreMap":80},[59,142,144,148,151],{"number":143},"5",[63,145,147],{"id":146},"update-your-application-connection-string","Update your application connection string",[18,149,150],{},"Add authentication to your MongoDB connection:",[71,152,155],{"className":153,"code":154,"language":76},[74],"// Connection string format\nmongodb://username:password@host:port/database?authSource=admin\n\n// Example for local development\nmongodb://myapp:mypassword@localhost:27017/myappdb\n\n// With options\nmongodb://myapp:mypassword@localhost:27017/myappdb?authSource=myappdb&retryWrites=true\n\n// In Node.js with Mongoose\nimport mongoose from 'mongoose';\n\nawait mongoose.connect(process.env.MONGODB_URI, {\n  // Connection options are included in the URI\n});\n\n// Or with explicit options\nawait mongoose.connect('mongodb://localhost:27017/myappdb', {\n  user: process.env.MONGO_USER,\n  pass: process.env.MONGO_PASSWORD,\n  authSource: 'myappdb'\n});\n",[78,156,154],{"__ignoreMap":80},[59,158,160,164,167],{"number":159},"6",[63,161,163],{"id":162},"set-up-role-based-access-for-teams","Set up role-based access for teams",[18,165,166],{},"Create custom roles for different access levels:",[71,168,171],{"className":169,"code":170,"language":76},[74],"use myappdb\n\n// Create a custom role for developers\ndb.createRole({\n  role: \"developer\",\n  privileges: [\n    {\n      resource: { db: \"myappdb\", collection: \"\" },\n      actions: [\"find\", \"insert\", \"update\", \"createIndex\"]\n    }\n  ],\n  roles: []\n})\n\n// Create developer user\ndb.createUser({\n  user: \"dev_john\",\n  pwd: passwordPrompt(),\n  roles: [{ role: \"developer\", db: \"myappdb\" }]\n})\n\n// Create a read-only role for analytics\ndb.createRole({\n  role: \"analyst\",\n  privileges: [\n    {\n      resource: { db: \"myappdb\", collection: \"\" },\n      actions: [\"find\", \"listCollections\"]\n    }\n  ],\n  roles: []\n})\n",[78,172,170],{"__ignoreMap":80},[174,175,176,179],"warning-box",{},[18,177,178],{},"Security Best Practices:",[31,180,181,184,187,190,193,196],{},[34,182,183],{},"Never use the admin user for application connections - create separate users",[34,185,186],{},"Use strong, unique passwords (20+ characters, mixed case, numbers, symbols)",[34,188,189],{},"Store credentials in environment variables, never in code",[34,191,192],{},"Enable TLS/SSL for connections, especially over networks",[34,194,195],{},"Bind MongoDB to localhost or specific IPs, not 0.0.0.0",[34,197,198],{},"Regularly rotate credentials and audit user access",[44,200,202],{"id":201},"how-to-verify-it-worked","How to Verify It Worked",[204,205,206,213,219,225],"ol",{},[34,207,208,212],{},[209,210,211],"strong",{},"Test rejected connection:"," Try connecting without credentials",[34,214,215,218],{},[209,216,217],{},"Test successful connection:"," Connect with your app user",[34,220,221,224],{},[209,222,223],{},"Test permission limits:"," Verify the app user can't access other databases",[34,226,227,230],{},[209,228,229],{},"Check server logs:"," Review auth success/failure in mongod logs",[71,232,235],{"className":233,"code":234,"language":76},[74],"# This should fail\nmongosh --eval \"db.stats()\"\n\n# This should succeed\nmongosh -u myapp -p yourpassword --authenticationDatabase myappdb myappdb --eval \"db.stats()\"\n\n# Try accessing admin database with app user (should fail)\nmongosh -u myapp -p yourpassword --authenticationDatabase myappdb admin --eval \"db.getUsers()\"\n",[78,236,234],{"__ignoreMap":80},[44,238,240],{"id":239},"common-errors-troubleshooting","Common Errors & Troubleshooting",[242,243,245],"h4",{"id":244},"error-authentication-failed","Error: \"Authentication failed\"",[18,247,248],{},"Check username, password, and authSource. The authSource must match the database where the user was created.",[242,250,252],{"id":251},"error-not-authorized-on-admin-to-execute-command","Error: \"not authorized on admin to execute command\"",[18,254,255],{},"You're trying to perform an admin operation with a non-admin user. Use the admin account or grant necessary roles.",[242,257,259],{"id":258},"cant-connect-after-enabling-auth","Can't connect after enabling auth",[18,261,262,263,266],{},"Make sure you created the admin user BEFORE enabling authorization. If locked out, restart MongoDB with ",[78,264,265],{},"--noauth"," flag, create the user, then restart normally.",[242,268,270],{"id":269},"mongoose-connection-timeout","Mongoose connection timeout",[18,272,273],{},"Check that the authSource in your connection string matches where the user was created (usually the app database or admin).",[275,276,277,284,290],"faq-section",{},[278,279,281],"faq-item",{"question":280},"Should I use MongoDB Atlas instead of self-hosted?",[18,282,283],{},"For most startups, yes. Atlas handles authentication, encryption, backups, and scaling automatically. Self-host only if you have specific compliance requirements or significant DevOps expertise.",[278,285,287],{"question":286},"What's the difference between authSource and the database name?",[18,288,289],{},"authSource is where MongoDB looks up the user credentials. The database name is what database you're connecting to. They can be different - many setups create users in the admin database but connect to app databases.",[278,291,293],{"question":292},"How do I enable TLS/SSL for MongoDB connections?",[18,294,295,296,299,300,303],{},"Add TLS configuration to mongod.conf and use ",[78,297,298],{},"mongodb+srv://"," or add ",[78,301,302],{},"?tls=true"," to your connection string. Atlas enables TLS by default.",[18,305,306,309,314,315,314,319],{},[209,307,308],{},"Related guides:",[310,311,313],"a",{"href":312},"/blog/how-to/postgresql-roles","PostgreSQL Roles Setup"," ·\n",[310,316,318],{"href":317},"/blog/how-to/database-encryption","Database Encryption",[310,320,322],{"href":321},"/blog/how-to/connection-pooling","Connection Pooling",[324,325,326,332,337],"related-articles",{},[327,328],"related-card",{"description":329,"href":330,"title":331},"Methods to verify your API keys aren't exposed in your codebase, git history, browser bundle, or network requests. Find ","/blog/how-to/check-exposed-keys","How to Check for Exposed API Keys",[327,333],{"description":334,"href":335,"title":336},"Complete guide to securing Clerk authentication. Set up middleware, protect routes, verify webhooks, manage users secure","/blog/how-to/clerk-security","How to Secure Clerk Authentication",[327,338],{"description":339,"href":321,"title":340},"Step-by-step guide to database connection pooling. Improve performance and security with PgBouncer, Prisma, and serverle","How to Set Up Database Connection Pooling",{"title":80,"searchDepth":342,"depth":342,"links":343},2,[344,345,354,355],{"id":46,"depth":342,"text":47},{"id":56,"depth":342,"text":57,"children":346},[347,349,350,351,352,353],{"id":65,"depth":348,"text":66},3,{"id":89,"depth":348,"text":90},{"id":105,"depth":348,"text":106},{"id":130,"depth":348,"text":131},{"id":146,"depth":348,"text":147},{"id":162,"depth":348,"text":163},{"id":201,"depth":342,"text":202},{"id":239,"depth":342,"text":240},"how-to","2026-01-19","Step-by-step guide to configuring MongoDB authentication. Create users, set up roles, enable access control, and secure your database connections.",false,"md",null,"yellow",{},true,"Step-by-step guide to MongoDB authentication and user management.","/blog/how-to/mongodb-auth","[object Object]","HowTo",{"title":5,"description":358},{"loc":366},"blog/how-to/mongodb-auth",[],"summary_large_image","WgwKd4756JRfFZYKiJckTyhaFGFSaUY4sYm3LMb_ikc",1775843928227]