Technology Encyclopedia Home >How to apply for security credentials in MongoDB?

How to apply for security credentials in MongoDB?

To apply for security credentials in MongoDB, you need to configure authentication and authorization mechanisms. Here's a step-by-step guide:

  1. Enable Authentication:

    • Start MongoDB with the --auth parameter or set security.authorization: enabled in the configuration file (mongod.conf).
    • Example:
      security:
        authorization: enabled
      
  2. Create User Accounts:

    • Connect to MongoDB (without authentication if not yet enabled) and switch to the admin database.
    • Use the db.createUser() method to create users with roles.
    • Example:
      use admin
      db.createUser({
        user: "adminUser",
        pwd: "securePassword",
        roles: ["root"]
      })
      
  3. Assign Roles:

    • MongoDB provides built-in roles (e.g., read, readWrite, dbAdmin) or custom roles.
    • Example (granting read-write access to a specific database):
      use myDatabase
      db.createUser({
        user: "appUser",
        pwd: "appPassword",
        roles: ["readWrite"]
      })
      
  4. Connect Using Credentials:

    • Use the mongo shell or a driver with the username and password.
    • Example (shell):
      mongo -u adminUser -p securePassword --authenticationDatabase admin
      

For managed MongoDB services like Tencent Cloud Database for MongoDB, credentials are typically auto-generated during instance creation. You can manage users and permissions via the Tencent Cloud console or API.

Example (Tencent Cloud):

  • Log in to the Tencent Cloud console, navigate to Database for MongoDB, select your instance, and use the User Management feature to create or modify users.

Always follow the principle of least privilege when assigning roles.