Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

python - (Py)Mongo can connect remotely but unauthorised when connecting locally

I have a MongoDB instance on a Digital Ocean droplet. I can remote into it using PyMongo and Compass but connecting locally via PyMongo tells me I am unauthorised.

Authentication failed., full error: {'ok': 0.0, 'errmsg': 'Authentication failed.', 'code': 18, 'codeName': 'AuthenticationFailed'}

Roles

[
{
    "_id" : "admin.normaluser",
    "userId" : ...,
    "user" : "normaluser",
    "db" : "admin",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "greedymercs"
        }
    ]
},
{
    "_id" : "admin.rootuser",
    "userId" : ...,
    "user" : "rootuser",
    "db" : "admin",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}

]

I can connect remotely using mongodb://normaluser:<pass>@<ip>:27017/ but connecting locally via mongodb://normaluser:<pass>@localhost:27017/fails. I have tried with a default database, rootuser etc and its the same issue every time.

mongood.conf

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1,<public ip>

#security:
security:
  authorization: enabled

Script I am using to test local connections

import os
import time

from pymongo import MongoClient

client = MongoClient(os.environ["MONGO_URI"])

now = time.time()

try:
    for i in range(100):
        client.greedymercs.mongoTest.insert_one({"number": i})

except Exception as e:
    print(e)

else:
    print("100 inserts:", time.time() - now)

now = time.time()

try:
    results = list(client.greedymercs.mongoTest.find({}))

except Exception as e:
    print(e)

else:
    print(f"Find all ({len(results)}):", time.time() - now)
question from:https://stackoverflow.com/questions/65862068/pymongo-can-connect-remotely-but-unauthorised-when-connecting-locally

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Added ?authSource=admin fixed the issue :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...