Authentication failed when using flask_pymongo

If you are using Flask-MongoEngine and setting mongo config using app.config['MONGODB_*'] then, your uri will be generated from those variables e.g.

app.config['MONGODB_DB'] = 'project1'
app.config['MONGODB_HOST'] = '192.168.1.35'
app.config['MONGODB_PORT'] = 12345
app.config['MONGODB_USERNAME'] = 'webapp'
app.config['MONGODB_PASSWORD'] = 'pwd123'

However, if you need to add some additional paramters (such query parameter authSource=admin) to uri then, you will have to pass mongo config through app.config['MONGODB_SETTINGS']

app.config['MONGODB_SETTINGS'] = {
    'connect': False,
    'host': 'mongodb://webapp:[email protected]:12345/project1?authSource=admin'
}

The problem is if you use the MONGO_URI config parameter then pymongo attempts to authenticate against the db name included in the string. You should break up the config parameters into the following so you can specify a db name and an auth source.

app.config['MONGO_HOST'] = 'localhost'
app.config['MONGO_PORT'] = '27017'
app.config['MONGO_DBNAME'] = 'mongo_test'
app.config['MONGO_USERNAME'] = 'root'
app.config['MONGO_PASSWORD'] = 'aaa2016'
app.config['MONGO_AUTH_SOURCE'] = 'admin' . # root user is typically defined in admin db

This question may be old, but I was experiencing the same issue and found another solution that might work for others.

Appending ?authSource=admin to the end of your MONGO_URI variable will authenticate your credentials against the admin database, rather than the one you're connecting to.

Example: app.config["MONGO_URI"] = "mongodb://username:password@host:port/db_name?authSource=admin"