How to avoid @ in password in pymongo connection?

My question is the specification, how can I verify the user password for mongodb authentication through pymongo? .

I am trying to connect to an instance of MongoDB using PyMongo 3.2.2 and an url containing the user and password, as described in MongoDB Docs . The difference is that the password I use contains "@".

At first, I just tried to connect without escaping, for example:

prefix = 'mongodb: //'

user = 'user: passw_with _ @_'

suffix = '@ 127.0.0.1: 27001 /'

conn = pymongo.MongoClient (prefix + user + suffix)

Naturally, I got the following error:

InvalidURI: ':' or '@' characters in a username or password must be escaped according to RFC 2396. 

So, I tried to escape from the user: pass the part using urllib.quote () as follows:

prefix = 'mongodb: //'

user = urllib.quote ('user: passw_with _ @_')

suffix = '@ 127.0.0.1: 27001 /'

conn = pymongo.MongoClient (prefix + user + suffix)

but then I got:

 OperationFailure: Authentication failed. 

(It’s important to say that using the MongoDB Management Tool GUI ( Robomongo , if that matters), I can connect to MongoDB using the (real) address and credentials.)

Print the user variable in the above code a 'user:passw_with_%40_' String (that is, "@" has become "% 40") and according to wikipedia , that is the expected acceleration.

I even tried to exit @ with a single and double backslash ( user = 'user:passw_with_\\@_' and user = 'user:passw_with_\@_' ), but they did not execute with the exception InvalidURI.

TL DR;

My question is: how can I avoid the "@" in the password portion of the MongoDB URL?

+6
source share
1 answer

You can avoid the password by using urllib.quote() . Although you should only specify / exclude the password and exclude username: otherwise : will also be escaped in %3A .

For instance:

 import pymongo import urllib mongo_uri = "mongodb://username:" + urllib.quote(" p@ssword ") + "@127.0.0.1:27001/" client = pymongo.MongoClient(mongo_uri) 

The above snippet has been tested for MongoDB v3.2.x, Python v2.7 and PyMongo v3.2.2.

The above example in the MongoDB URI line:

  • The user is created in the admin database.
  • mongod host runs 127.0.0.1 (localhost)
  • The assigned mongod port is 27001
+13
source

All Articles