Skip to content

Instantly share code, notes, and snippets.

@rajiff
Last active January 16, 2019 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajiff/7bdb16bd77c45c3e9f0a7f83d42425cb to your computer and use it in GitHub Desktop.
Save rajiff/7bdb16bd77c45c3e9f0a7f83d42425cb to your computer and use it in GitHub Desktop.
Application Authentication wit MongoDB

Hosting a MongoDB and creating accounts for application in it

  1. Docker Compose is only for creating root account in db admin, this is not the database for application

  2. Create Application specific accounts and set the authentication details

    2.1 Login to MongoDB using root credentials and use below syntax to create application specific account and the database

    2.2 Application should use its own DB and Credentials

Syntax for creating an account for application

PS: You have to be in the database for which you are creating the credentials

use <application db name>
db.createUser({user: "<application db username>", pwd: "<application db pwd>", roles: ["readWrite", "dbAdmin"]});

Eg:

use sampleapp
db.createUser({user: "myuser", pwd: "mypwd", roles: ["readWrite", "dbAdmin"]});

You can use docker compose like below to host a DB

version: '3.1'
  
services:

  mongo:
    image: mongo:latest
    restart: always
    ports:
      - 27017:27017
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

You can use this command to login to admin account, which will prompt for password

mongo --host <whatever is the hostname> -u root --password --authenticationDatabase admin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment