Pymongo keep failing to login MongoDB. I typed right password for "root" account.
Traceback (most recent call last):
File "index.py", line 3, in <module>
from apis import app
File "/home/app/apis/__init__.py", line 16, in <module>
import apis.call
File "/home/app/apis/call.py", line 12, in <module>
import auth
File "/home/app/apis/auth.py", line 18, in <module>
connection.api.authenticate(database.ADMIN_ID,database.ADMIN_PASSWD)
File "/usr/lib64/python2.6/site-packages/pymongo/database.py", line 875, in authenticate
self.connection._cache_credentials(self.name, credentials)
File "/usr/lib64/python2.6/site-packages/pymongo/mongo_client.py", line 456, in _cache_credentials
auth.authenticate(credentials, sock_info, self.__simple_command)
File "/usr/lib64/python2.6/site-packages/pymongo/auth.py", line 243, in authenticate
auth_func(credentials[1:], sock_info, cmd_func)
File "/usr/lib64/python2.6/site-packages/pymongo/auth.py", line 222, in _authenticate_mongo_cr
cmd_func(sock_info, source, query)
File "/usr/lib64/python2.6/site-packages/pymongo/mongo_client.py", line 687, in __simple_command
helpers._check_command_response(response, None, msg)
File "/usr/lib64/python2.6/site-packages/pymongo/helpers.py", line 178, in _check_command_response
raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: command SON([('authenticate', 1), ('user', u'root'), ('nonce', u'9e44852e6597a1de'), ('key', u'f132369d21874c9858409e235abff25f')]) failed: auth failed
Here is pymongo
import pymongo
connection = pymongo.MongoClient("127.0.0.1")
connection.api.authenticate("root","1234")
db = connection.api
does pymongo use md5 on password? it looks like there is some different password in mongodb data.
here is mongodb admin system.users data
{
"user": "root",
"pwd": "cde0d84e6749c235a3b4e36d945eb6fe",
"roles": [
"userAdminAnyDatabase"
]
}
Do you see what is wrong?
In my case, I upgraded pymongo
pip install --upgrade pymongo
I tried to connect table called api.
connection.api.authenticate("root","1234")
There wasn't admin account in api table. I did put in system.admin table. So, I created a new admin account in api table and it worked.
Looks like you have to cut the certificate from the Bluemix MongoDB Credentials, save in a file (e.g. certificate.pem), and refer to it as follows:
client = pymongo.MongoClient(uri_string, ssl_ca_certs='c:\data\certificate.pem')
Related
I am using MongoDB atlas for my discord bot but recently ran into an error. On the hosting (Heroku) everything works without errors, I first updated all the modules, but the error has not disappeared.
I am using motor as a driver to work with MongoDB atlas.
Checked the database connection URL, everything is correct.
Python version 3.10(on Heroku too)
Traceback (most recent call last):
File "D:\Проекты\AkainuBot\main.py", line 23, in <module>
mongo = AsyncIOMotorClient(
File "D:\Python\lib\site-packages\motor\core.py", line 159, in __init__
delegate = self.__delegate_class__(*args, **kwargs)
File "D:\Python\lib\site-packages\pymongo\mongo_client.py", line 718, in __init__
self.__options = options = ClientOptions(
File "D:\Python\lib\site-packages\pymongo\client_options.py", line 165, in __init__
self.__pool_options = _parse_pool_options(options)
File "D:\Python\lib\site-packages\pymongo\client_options.py", line 132, in _parse_pool_options
ssl_context, ssl_match_hostname = _parse_ssl_options(options)
File "D:\Python\lib\site-packages\pymongo\client_options.py", line 98, in _parse_ssl_options
ctx = get_ssl_context(
File "D:\Python\lib\site-packages\pymongo\ssl_support.py", line 159, in get_ssl_context
ctx.load_verify_locations(certifi.where())
File "D:\Python\lib\site-packages\pymongo\pyopenssl_context.py", line 276, in load_verify_locations
self._callback_data.trusted_ca_certs = _load_trusted_ca_certs(cafile)
File "D:\Python\lib\site-packages\pymongo\ocsp_support.py", line 79, in _load_trusted_ca_certs
_load_pem_x509_certificate(cert_data, backend))
File "D:\Python\lib\site-packages\cryptography\x509\base.py", line 436, in load_pem_x509_certificate
return rust_x509.load_pem_x509_certificate(data)
ValueError: error parsing asn1 value: ParseError { kind: InvalidValue, location: ["RawCertificate::tbs_cert", "TbsCertificate::serial"] }
I've solved my problem getting the parsing asn1 value error by adding the ssl_cert_reqs option on the MongoClient (and obviously importing ssl).
dbClient = pymongo.MongoClient(uri, ssl_cert_reqs=ssl.CERT_NONE)
I am building a python client-side application that uses Firestore. I have successfully used Google Identity Platform to sign up and sign in to the Firebase project, and created a working Firestore client using google.cloud.firestore.Client which is authenticated as a user:
import json
import requests
import google.oauth2.credentials
from google.cloud import firestore
request_url = f"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key={self.__api_key}"
headers = {"Content-Type": "application/json; charset=UTF-8"}
data = json.dumps({"email": self.__email, "password": self.__password, "returnSecureToken": True})
response = requests.post(request_url, headers=headers, data=data)
try:
response.raise_for_status()
except (HTTPError, Exception):
content = response.json()
error = f"error: {content['error']['message']}"
raise AuthError(error)
json_response = response.json()
self.__token = json_response["idToken"]
self.__refresh_token = json_response["refreshToken"]
credentials = google.oauth2.credentials.Credentials(self.__token,
self.__refresh_token,
client_id="",
client_secret="",
token_uri=f"https://securetoken.googleapis.com/v1/token?key={self.__api_key}"
)
self.__db = firestore.Client(self.__project_id, credentials)
I have the problem, however, that when the token has expired, I get the following error:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
return callable_(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/grpc/_channel.py", line 826, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/usr/local/lib/python3.7/dist-packages/grpc/_channel.py", line 729, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.UNAUTHENTICATED
details = "Missing or invalid authentication."
debug_error_string = "{"created":"#1613043524.699081937","description":"Error received from peer ipv4:172.217.16.74:443","file":"src/core/lib/surface/call.cc","file_line":1055,"grpc_message":"Missing or invalid authentication.","grpc_status":16}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/home/my_app/src/controllers/im_alive.py", line 20, in run
self.__device_api.set_last_updated(utils.device_id())
File "/home/my_app/src/api/firestore/firestore_device_api.py", line 21, in set_last_updated
"lastUpdatedTime": self.__firestore.SERVER_TIMESTAMP
File "/home/my_app/src/api/firestore/firestore.py", line 100, in update
ref.update(data)
File "/usr/local/lib/python3.7/dist-packages/google/cloud/firestore_v1/document.py", line 382, in update
write_results = batch.commit()
File "/usr/local/lib/python3.7/dist-packages/google/cloud/firestore_v1/batch.py", line 147, in commit
metadata=self._client._rpc_metadata,
File "/usr/local/lib/python3.7/dist-packages/google/cloud/firestore_v1/gapic/firestore_client.py", line 1121, in commit
request, retry=retry, timeout=timeout, metadata=metadata
File "/usr/local/lib/python3.7/dist-packages/google/api_core/gapic_v1/method.py", line 145, in __call__
return wrapped_func(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/google/api_core/retry.py", line 286, in retry_wrapped_func
on_error=on_error,
File "/usr/local/lib/python3.7/dist-packages/google/api_core/retry.py", line 184, in retry_target
return target()
File "/usr/local/lib/python3.7/dist-packages/google/api_core/timeout.py", line 214, in func_with_timeout
return func(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.Unauthenticated: 401 Missing or invalid authentication.
I have tried omitting the token and only specifying the refresh token, and then calling credentials.refresh(), but the expires_in in the response from the https://securetoken.googleapis.com/v1/token endpoint is a string instead of a number (docs here), which makes _parse_expiry(response_data) in google.oauth2._client.py:257 raise an exception.
Is there any way to use the firestore.Client from either google.cloud or firebase_admin and have it automatically handle refreshing tokens, or do I need to switch to the manually calling the Firestore RPC API and refreshing tokens at the correct time?
Note: There are no users interacting with the python app, so the solution must not require user interaction.
Can't you just pass the string cast as integer _parse_expiry(int(float(response_data))) ?
If it is not working you could try to make a call and refresh token after getting and error 401, see my answer for the general idea on how to handle tokens.
As mentioned by #Marco, it is recommended that you use a service account if it's going to be used in an environment without user. When you use service account, you can just set GOOGLE_APPLICATION_CREDENTIALS environment variable to location of service account json file and just instantiate the firestore Client without any credentials (The credentials will be picked up automatically):
import firestore
client = firestore.Client()
and run it as (assuming Linux):
$ export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json
$ python file.py
Still, if you really want to use user credentials for the script, you can install the Google Cloud SDK, then:
$ gcloud auth application-default login
This will open browser and for you to select account and login. After logging in, it creates a "virtual" service account file corresponding to your user account (that will also be loaded automatically by clients). Here too, you don't need to pass any parameters to your client.
See also: Difference between “gcloud auth application-default login” and “gcloud auth login”
I am trying to make an api connection via wsdl-soap in Python.
Here are the codes I used.
import zeep
wsdl = 'http://dev.gittigidiyor.com:8080/listingapi/ws/CategoryService?wsdl'
client = zeep.Client(wsdl=wsdl)
send_data=[{
'cat:getCategories' :[
{
'startOffSet' : 0,
'rowCount' : 4,
'withSpecs':'true',
'withDeepest':'true',
'withCatalog':'true',
'lang':'tr'
}
] } ]
print(client.service.getCategories(send_data))
The offical documentation suggests:
WSDL Address: http://dev.gittigidiyor.com:8080/listingapi/ws/CategoryService?wsdl
Service Method Signature: CategoryServiceResponse getCategories(int startOffSet, int rowCount, boolean withSpecs, boolean withDeepest, boolean withCatalog, String lang)
Request Example
<cat:getCategories>
<startOffSet>0</startOffSet>
<rowCount>4</rowCount>
<withSpecs>true</withSpecs>
<withDeepest>true</withDeepest>
<withCatalog>true</withCatalog>
<lang>tr</lang>
</cat:getCategories>
However I can't achieve to get any data from the source. I am getting errors like:
Traceback (most recent call last):
File "/Users/maydin/Desktop/z.py", line 22, in <module>
print(client.service.getCategories(send_data))
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/proxy.py", line 42, in __call__
self._op_name, args, kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/wsdl/bindings/soap.py", line 115, in send
options=options)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/wsdl/bindings/soap.py", line 68, in _create
serialized = operation_obj.create(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/wsdl/definitions.py", line 200, in create
return self.input.serialize(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/wsdl/messages/soap.py", line 65, in serialize
self.body.render(body, body_value)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/xsd/elements/element.py", line 191, in render
self._render_value_item(parent, value, render_path)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/xsd/elements/element.py", line 215, in _render_value_item
return self.type.render(node, value, None, render_path)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/xsd/types/complex.py", line 253, in render
element.render(parent, element_value, child_path)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/xsd/elements/indicators.py", line 241, in render
element.render(parent, element_value, child_path)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/xsd/elements/element.py", line 185, in render
self.validate(value, render_path)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/zeep/xsd/elements/element.py", line 236, in validate
"Missing element %s" % (self.name), path=render_path)
zeep.exceptions.ValidationError: Missing element rowCount (getCategories.rowCount)
>>>
Any help (new library suggestions, code correction etc.) will be appriciated.
Thanks in advance!
I finally solved my own problem.. The thing that I have missed is that it was needing an authentication layer.
Here are the codes for those who may need to solve similar problems.
from requests import Session
from requests.auth import HTTPBasicAuth
from zeep import Client
from zeep.transports import Transport
session = Session()
session.auth = HTTPBasicAuth('user_name', 'password')
client = Client('wsdl_url',
transport=Transport(session=session))
print(client.service.service_name(parameter1,parameter2,parameter3..))
Here is the source I made use of..
I am trying to connect to my mongodb in mlab.com using flask but when I run my flask script I am getting Authentication failed error, please help.
my code:
from flask import Flask, jsonify, request
from flask_pymongo import PyMongo
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'mydb'
app.config['MONGO_URI'] = 'mongodb://user:pwd#ds157799.mlab.com:57799/mydb'
mongo = PyMongo(app)
#app.route('/framework', methods=['GET'])
def get_all_frameworks():
framework = mongo.db.framework
output = []
for q in framework.find():
output.append({'name' : q['name'], 'language' : q['language']})
return jsonify({'result' : output})
Error:
File "mongo.py", line 12, in <module>
mongo = PyMongo(app)
File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\flask_pymongo\__init__.py", line 97, in __init__
self.init_app(app, config_prefix)
File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\flask_pymongo\__init__.py", line 283, in init_app
mechanism=auth_mechanism)
File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\database.py", line 1167, in authenticate
connect=True)
File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\mongo_client.py", line 588, in _cache_credentials
sock_info.authenticate(credentials)
File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\pool.py", line 620, in authenticate
auth.authenticate(credentials, self)
File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\auth.py", line 486, in authenticate
auth_func(credentials, sock_info)
File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\auth.py", line 237, in _authenticate_scram_sha1
res = sock_info.command(source, cmd)
File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\pool.py", line 517, in command
collation=collation)
File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\network.py", line 125, in command
parse_write_concern_error=parse_write_concern_error)
File "C:\Users\ELCOT\AppData\Local\Programs\Python\Python35\lib\site-packages\pymongo\helpers.py", line 145, in _check_command_response
raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: Authentication failed.
Please help to resolve this.
You can use this as an alternative to sign in to your database. This is tested and works :
connection = pymongo.MongoClient(HOST, PORT)
db = connection[databasename]
db.authenticate(database_user, database_pass)
I created a new user with password for my db, and worked fine.
https://www.reddit.com/r/flask/comments/5ftqvm/how_to_use_pymongo_with_hosted_mongodb_mlab/
This Works fine. For me connecting via URI string from mLab database doesn't work as well.
I'm currently trying to deploy a website built with the Python Flask framework to Webfaction. I've deployed a MongoDB to which I can succesfully connect from the MongoDB interactive interpreter:
[celli#web498 ~]$ mongo localhost:18209/admin
MongoDB shell version: 3.0.2
connecting to: localhost:18209/admin
> db.auth("awesomeusername", "anawesomepassword")
1
When starting the website, it can successfully connect using these credentials in my flask config.py file:
MONGODB_SETTINGS = {
'db': 'tc',
'port': 18209,
'username': 'awesomeusername',
'password': 'anawesomepassword',
}
But when I visit a page which does a query I get the error below. This code works perfectly well on another server, so the mistake lies somewhere in either the setup of my MongoDB instance, or in the connection to it. I also find it strange that setting up the connection works fine, but querying it creates this Authentication failed error.
Any idea how I can fix this? All tips are welcome!
File "/home/celli/webapps/tc/venv/lib/python2.7/site-packages/flask_login.py", line 758, in decorated_view
return func(*args, **kwargs)
File "/home/celli/webapps/tc/tc/app/views/webviews.py", line 220, in myTickets
userDocs = UserDocument.objects(id__in=[ticket.doc_id for ticket in userTickets])
File "/home/celli/webapps/tc/venv/lib/python2.7/site-packages/mongoengine/queryset/manager.py", line 37, in __get__
queryset = queryset_class(owner, owner._get_collection())
File "/home/celli/webapps/tc/venv/lib/python2.7/site-packages/mongoengine/document.py", line 168, in _get_collection
db = cls._get_db()
File "/home/celli/webapps/tc/venv/lib/python2.7/site-packages/mongoengine/document.py", line 162, in _get_db
return get_db(cls._meta.get("db_alias", DEFAULT_CONNECTION_NAME))
File "/home/celli/webapps/tc/venv/lib/python2.7/site-packages/mongoengine/connection.py", line 143, in get_db
source=conn_settings['authentication_source'])
File "/home/celli/webapps/tc/venv/lib/python2.7/site-packages/pymongo/database.py", line 978, in authenticate
self.connection._cache_credentials(self.name, credentials)
File "/home/celli/webapps/tc/venv/lib/python2.7/site-packages/pymongo/mongo_client.py", line 467, in _cache_credentials
auth.authenticate(credentials, sock_info, self.__simple_command)
File "/home/celli/webapps/tc/venv/lib/python2.7/site-packages/pymongo/auth.py", line 475, in authenticate
auth_func(credentials[1:], sock_info, cmd_func)
File "/home/celli/webapps/tc/venv/lib/python2.7/site-packages/pymongo/auth.py", line 450, in _authenticate_default
return _authenticate_scram_sha1(credentials, sock_info, cmd_func)
File "/home/celli/webapps/tc/venv/lib/python2.7/site-packages/pymongo/auth.py", line 238, in _authenticate_scram_sha1
sasl_start, sasl_continue)
File "/home/celli/webapps/tc/venv/lib/python2.7/site-packages/pymongo/auth.py", line 185, in _scram_sha1_conversation
res, _ = cmd_func(sock_info, source, sasl_start)
File "/home/celli/webapps/tc/venv/lib/python2.7/site-packages/pymongo/mongo_client.py", line 703, in __simple_command
helpers._check_command_response(response, None, msg)
File "/home/celli/webapps/tc/venv/lib/python2.7/site-packages/pymongo/helpers.py", line 182, in _check_command_response
raise OperationFailure(msg % errmsg, code, response)
OperationFailure: command SON([('saslStart', 1), ('mechanism', 'SCRAM-SHA-1'), ('autoAuthorize', 1), ('payload', Binary('n,,n=awesomeusername,r=NjAxNTEwMjc5MzAy', 0))]) on namespace tc.$cmd failed: Authentication failed.
MongoDB's users are per-database. In your example you show that you connect to the admin database, but the error message is simply telling you that your user is trying to authenticate with the tc database. Probably your user doesn't have a role on tc.
(The other possibility is that tc is not the database you want to connect to; you need to specify the correct database name in your connection params/string).