Exception: 401 Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential - python-3.x

I've seen a few people over the years facing similar issue but I haven't found much regarding my case.
I have a backend built with python3.
I am using firebase_admin as a library to connect to Firebase Cloud Firestore.
I then commit my code to Github and using Github Actions
I am deploying the docker container to Google Cloud Run.
This all works fine for some time
Some time later throws the following exception: Exception: 401 Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
What am I doing wrong?
Should I connect every time I call the function? (move the db initialization in each function call)
Feels like the token expired. Can I refresh it somehow?
Python code:
from firebase_admin import firestore, initialize_app
initialize_app()
db = firestore.client()
def get_info_from_firestore(name: str:
try:
data = db.collection(u'data').where(u'title', u'==', name).stream()
for rating in ratings:
return rating.to_dict()
return None
except Exception as e:
logging.warning(Exception: {e}')
return None
And this file is imported from my root python file that's using Flask.
Edit: One final thing that might help, if I redeploy my container without any changes it all works again.

Likely this is happening due to time drift: time in docker significatly differs realtime. After restart time is in sync but after a while it drifts. Google does not like it. See more info about this WSL/container issue here https://github.com/microsoft/WSL/issues/4245 and here https://github.com/docker/for-win/issues/4526

Related

How can I fix the error: 'an existing connection was forcibly closed'. (Office 365 REST Python client)

I recently created a solution to automate some copy-pasting of Excel files between SharePoint folders.
To establish the connection to SharePoint, I use the Office 365 REST Python client.
As an authentication method, I use clientcredentials (this allowed me to bypass TFA on the SharePoint).
I have verified that the ID and secret that I am using are still valid.
Until recently, the code was working like a charm.
Yesterday, however, I got the following error (and have been getting it ever since):
Requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))
Weidly, sometimes I get the following error instead:
File "...\acs_token_provider.py", line
45, in get_app_only_access_token
self.error = e.response.text
AttributeError: 'NoneType' object has no attribute 'text'
I have encountered several posts mentioning the first error.
However, none of them were related to the package that I am using.
Below is a simplified example of my code which produces the same error:
from office365.runtime.auth.client_credential import ClientCredential
from office365.sharepoint.client_context import ClientContext
CLIENT_ID = "thecorrectclientid"
CLIENT_SECRET = "thecorrectclientsecret"
site_url = "https://{xxxx}.sharepoint.com/sites/{nameofthesite}"
ctx = ClientContext(site_url)
creds = ClientCredential(CLIENT_ID, CLIENT_SECRET)
ctx.with_credentials(creds)
web = ctx.web
ctx.load(web)
ctx.execute_query()
print("Web title: {0}".format(web.properties['Title']))
Does anyone have an idea what may be causing this and how I could possibly fix this?
Any help would be greatly appreciated!
UPDATE: It seems to be a problem related to my local machine.
I just cloned the repo on my other laptop and it runs smoothly.
I have also noticed the following error when opening files from SharePoint (which might be related):
the server you are trying to access is using an authentication protocol not supported by office sharepoint excel
I tried refreshing the Client Id and Client secret (to make sure I wasn't using expired credentials).
I have browsed the web for similar errors, but none of them gave me the answer for my specific situation.
I have double checked if anything changed in the URL of the site that I am trying to access.
I tried running it on another laptop and that worked for me. But the root cause is still a mystery.
No results...
UPDATE: I tried running it on another laptop and that worked for me. But the root cause is still a mystery.

FCM Python SDK - Request contains an invalid argument

For my mobile applications (Android and iOS), I am using Firebase Cloud Messaging (FCM) for push notifications.
My backend server, uses the FCM Admin Python SDK to send the notification to a particular device with some additional data. The code responsible for sending the notification is as follows:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import messaging
cred = credentials.Certificate('cert.json')
firebase_admin.initialize_app(cred)
def sendNotification(token, sessionId, authenticationUrl, deviceId):
# This registration token comes from the client FCM SDKs.
registration_token = token
message = messaging.Message(
token=registration_token,
data={
'sessionId': sessionId,
'authenticationUrl': authenticationUrl,
'deviceId': deviceId
},
android=messaging.AndroidConfig(ttl=0, priority='high'),
apns=messaging.APNSConfig(
headers={'apns-priority': '10'},
payload=messaging.APNSPayload(
aps=messaging.Aps(content_available=True)
)
)
)
# Send a message to the device corresponding to the provided registration token.
try:
response = messaging.send(message)
print('Successfully sent message:', response)
except Exception as e:
print(e)
Before, I had the follwing also as part of Aps object but I removed it as the message and body is generated by the mobile application now (depending on mobile language):
alert=messaging.ApsAlert(title='Authentication Request', body='Would you like to authenticate?')
Since removing the ApsAlert, the above code fails randomly with the error:
Request contains an invalid argument.
If I call the same function again without any changes, it succeeds after few attempts and again fails on some runs. There is no common pattern due to which this fails.
Is there a way, I can get some more information regarding the error in order to resolve it?
Maybe, which is the invalid arguement.
Update
Based on #Hiranya's comment, I added some error handling and I was able to determine for which arguement it returns "Invalid arguement".
It does that for registration_token but interestingly, the token is never modified during consecutive runs that fail and succeed.
So, still no clue regarding this behavior.
For info:
Python version: 3.8
firebase-admin version: 4.5.2

Getting Connection Reset Issue while Fetching Azure Access Token

hope everyone is well.
I am using azure library to fetch access token using the below code snippet, but getting an error
Execution of class com.microsoft.aad.msal4j.AcquireTokenByAuthorizationGrantSupplier failed.
com.microsoft.aad.msal4j.MsalClientException: java.net.SocketException: Connection reset
When I enclose the code in try catch, it gets catched as an ExecutionException.
Below is the code snippet.
ConfidentialClientApplication app = ConfidentialClientApplication.builder("XXX", ClientCredentialFactory.createFromCertificate(XXX, "")).authority("https://login.microsoftonline.com/XXX").build();
ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(Collections.singleton(String.format(https://graph.microsoft.com/.default))).build();
CompletableFuture future = app.acquireToken(clientCredentialParam);
//call to future.get() function
I appreciate if anyone could help me in this issue as I am unable to find any solution for this for the past 2 weeks, tried so many ways but no success.
Thanks

Jira authentication struggle

I'm using jira-python library to gain API access to our company account on Jira.
This is the block of code that should work according to the docs:
from jira.client import JIRA
jira = JIRA(options={'server': 'https://jira.xyz.co.uk'},
basic_auth=('marek#xyz.co.uk', 'my_token'))
Taking into account the fact that cookie-based authentication no longer works I generated API tokens and parsed them into code, yet I'm getting error:
WARNING:root:Got recoverable error from GET https://jira.xyz.co.uk/rest/api/2/serverInfo, will retry [2/3] in 5.527397890949137s. Err: 401
And this just loops and loops until I hit Ctrl+c.
I found this topic here Issue in connecting with JIRA python where somebody asked the very same question but the solution didn't work for me as the missing libraries aren't missing on my system.
What else I could try ?

Steam 2FA throwing "Failed to get a web session" consistantly

I'm using steam's python library to create an app for generating 2FA codes. The issue is that steam throws me this error whenever I try to add a phone number or add 2FA to said account:
RuntimeError: Failed to get a web session. Try again in a few minutes
Fri Mar 30 08:39:04 2018 <Greenlet at 0x6e64580: handle_after_logon> failed with RuntimeError
Yes I've waited a few minutes and have been trying for hours.
Here's the code that I'm using to attempt this:
from steam import SteamClient
from steam.enums.emsg import EMsg
from steam.guard import SteamAuthenticator
#Create our steamclient instance
client = SteamClient()
#client.on("logged_on")
def handle_after_logon():
print("You are now Logged in.")
#Setup Autenticator for our steamclient instance "client". "client" is our logged in SteamClient instance as requested by documentation
sa = SteamAuthenticator(medium=client)
#My account has no phone number
print(sa.has_phone_number())
#Adding phone number because I know ahead of time I don't have it
sa.add_phone_number("myphonenumber with area code")
sa.add() # SMS code will be sent to account's phone number
sa.secrets # dict with authenticator secrets
#We're gonna need these
print(sa.secrets)
sa.finalize(str(input("SMS CODE: "))) # activate the authenticator
sa.get_code() # generate 2FA code for login
sa.remove() # removes the authenticator from the account
try:
#Login to our steamclient instance
client.cli_login("myusername","mypassword")
#client.on("loggon_on") doesn't trigger without this
client.run_forever()
#Allow us to logout using keyboard interrupt
except KeyboardInterrupt:
if client.connected:
client.logout()
Due to a lack of example code on 2FA in particular I've followed the documentation the best I could, I've looked at all of the below:
http://steam.readthedocs.io/en/latest/api/steam.client.html
http://steam.readthedocs.io/en/latest/api/steam.guard.html
https://github.com/ValvePython/steam/blob/master/recipes/1.Login/persistent_login.py
I feel like there's simply a silly error in my code, but reading through the documentation doesn't appear to be helping me solve this.
Thanks for your guys help.
I debugged for a while and it's an issue with gevent
I added this line to fix it at the beginning of my script:
from gevent import monkey
monkey.patch_all(thread=False)

Resources