Firebase admin SDK Python - cannot verify custom tokens - python

I'm trying to play with the firebase admin sdk for python for making custom tokens and verify those while testing my app. Problem is that while I try to verify the token I always get such an error:
ValueError: Firebase ID token has incorrect "aud" (audience) claim. Expected "my_project_id" but got "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit". Make sure the ID token comes from the same Firebase project as the service account used to authenticate this SDK. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.
I followed the guide to create the app and making the tokens:
import firebase_admin
from firebase_admin import auth, credentials
cred = credentials.Certificate('/path/to/file.json')
app = firebase_admin.initialize(cred)
custom_token = auth.create_custom_token('some-uid', app=app)
auth.verify_id_token(custom_token, app=app)
and here I get the error. It seems that _TokenGenarator is initialised with the defaults that are coming back from the error. I thought when passing the app it should automatically change those but it's not happening. Am I missing something?

verify_id_token() only accepts ID tokens. Custom tokens do not fall into that category. See this test case. Raising a ValueError is the expected behavior in this case.
ID tokens can be obtained from a client SDK. You can exchange a custom token for an ID token by calling one of the provided signInWithCustomToken() methods.

Related

Django doesn't validate or see the JWT token from Azure

I used azure-ad-verify-token 0.2.1 on Django-rest backend to validate a jwt token from Microsoft Azure, where the user is authenticated on the frontend with React.
According to the documentation, this library should do everything on its own.
from azure_ad_verify_token import verify_jwt
azure_ad_app_id = 'my app id'
azure_ad_issuer = 'https://exampletenant.b2clogin.com/0867afa-24e7-40e9-9d27-74bb598zzzzc/v2.0/'
azure_ad_jwks_uri = 'https://exampletenant.b2clogin.com/exampletenant.onmicrosoft.com/B2C_1_app_sign_in/discovery/v2.0/keys'
payload = verify_jwt(
token='<AZURE_JWT_TO_VERIFY_HERE>',
valid_audiences=[azure_ad_app_id],
issuer=azure_ad_issuer,
jwks_uri=azure_ad_jwks_uri,
verify=True,
)
print(payload)
I don't understand the line token='<AZURE_JWT_TO_VERIFY_HERE>', how can I put the token there?
Authorization from Azure on React is successful, and I get a access jwt-token that I can extract:
token = request.headers['Authorization']
But I need to validate it and somehow insert it into a string token='<AZURE_JWT_TO_VERIFY_HERE>', but it doesn't recognize the request here.
How can I put a token= from the header?
And in general, is this the right way? Or am I missing something? Any help and hints would be very helpful and would be greatly appreciated. Or advise another library for token validation in Python.
azure-ad-verify-token This is used to verify the tokens received from azure ad.
You have to get auth tokens from azure using MSAL python library and the azure-ad-verify-token will then verify the token.
To retrieve the tokens, you will need MSAL python library, and it
will also take clientid and tenentd as arguments.
test_app=PublicClientApplication(client_id=client_id,authority="https://login.microsoftonline.com/"+tenant_id)
test_tokens=test_app.acquire_token_interactive(scopes=scopes)
Now you can take the token you just received and use it in theazure-ad-verify-token.
token=test_tokens['access_token']
Reference:
MSAL Python
Authenticate Python apps by using the Azure SDK for Python

Authorization error 403 with Twitter API using python [duplicate]

I attempted to run the code below and am getting an error that states:
HTTP Error code: 403: Forbidden: Authentication succeeded but account is not authorized to access this resource.
from searchtweets import ResultStream, gen_rule_payload, load_credentials, collect_results
import requests
premium_search_args = load_credentials("/home/dirname/twitter_keys.yaml",
yaml_key="search_tweets_premium",
env_overwrite=False)
rule = gen_rule_payload("basketball", results_per_call=100) # testing with a sandbox account
print(rule)
from searchtweets import collect_results
tweets = collect_results(rule,
max_results=100,
result_stream_args=premium_search_args)
# print(tweets.all_text)
[print(tweet.all_text, end='\n\n') for tweet in tweets[0:10]];
My YAML file looks like this:
search_tweets_premium:
account_type: premium
endpoint: https://api.twitter.com/1.1/tweets/search/fullarchive/dev.json
consumer_key: AAAAAAAAAAAAAAAAAAAAA
consumer_secret: BBBBBBBBBBBBBBBBBBBBBBBBBBB
Only other thing to note is that I am using the free/sandbox service.
Any ideas if I am doing anything wrong in the code, the YAML, and/or within my Twitter developer account?
You'll need to go to https://developer.twitter.com/en/account/environments
There you should be able to see the various development environments that you have. You can create one should they not have been created.
The dev environment label would then be the thing you use to replace in your endpoint.
In my example, it would be:
https://api.twitter.com/1.1/tweets/search/fullarchive/development.json
If that still doesn't work, you might need to include a bearer token in your YAML file.

Getting 401 Client Error when using firebase

I'm new to firebase and I'm trying to update some data in an existing project but I'm getting the following error: 401 Client Error: Unauthorized for url. So how to fix this problem and thank you! I just want to mention also that I have been added to the project, so I'm not the owner.
this is my code:
from firebase import firebase
firebase = firebase.FirebaseApplication("the http path", None) # None bcz we are testing
firebase.put("/esco-lebanon/device-configs/atest-dev", "brightness", 50)
print("Updated")
According to the documentation, a 401 error means one of the following:
The auth token has expired.
The auth token used in the request is invalid.
Authenticating with an access_token failed.
The request violates your Firebase Realtime Database Rules.
The understanding here is that your client code needs to correctly identify a Firebase Authentication user with a token in access_token, and that user account must have access to read the data in the database according to its security rules. Since you haven't provided a token, your access is coming in anonymously, so you could only query data where security rules allow universal access.
If you haven't investigated using authentication in your request, you should read the documentation about that.

Firebase Admin SDK - Python

Recently the FB Admin SDK was introduced for Python as well, and here is a repo with some samples.
It's nice I can authenticate using credentials, and finally I have a firebase_admin authenticated which can create Custom Tokens too. But how can it help to do requests for the REST API e.g? Can I retrieve my authentication token and set it as Authorization header maybe to do API requests?
You should be able to get an OAuth token by calling the get_access_token() method on your credential, and then pass it to the REST API as described here.
However, in the v1.0.0 of the Python Admin SDK, the returned credential does not contain the Firebase scopes. Therefore the OAuth token obtained from the credential will not readily work with the REST API. This is a bug, and it will be addressed in a future release. In the meantime you can use the following trick:
from firebase_admin import credentials
scopes = [
'https://www.googleapis.com/auth/firebase.database',
'https://www.googleapis.com/auth/userinfo.email'
]
cred = credentials.Certificate('path/to/serviceKey.json')
token = cred.get_credential().create_scoped(scopes).get_access_token().access_token
# Pass token to REST API
In a future release, once the bug has been fixed, you will be to do the following:
from firebase_admin import credentials
cred = credentials.Certificate('path/to/serviceKey.json')
token = cred.get_access_token().access_token
# Pass token to REST API

Getting user info with Cloud Endpoints (using other API Endpoints)

I'm trying to setup endpoints api (with google app engine, python), but I'm having some trouble getting user profile info. API is working, I can create entities through API Explorer on my localhost.
My goal is to allow user to register for my app by providing just an email, and authorizing the app to get the reset of the info from their profile. I have this endpoints method:
#User.method(http_method="POST",
auth_level=endpoints.AUTH_LEVEL.REQUIRED,
allowed_client_ids=[
endpoints.API_EXPLORER_CLIENT_ID
],
scopes=[
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/plus.me',
],
user_required=True,
request_fields=('email',),
response_fields=('id',),
name="register",
path="users")
def UserRegister(self, instance):
logging.info(os.getenv( 'HTTP_AUTHORIZATION' ))
# 'Beared __TOKEN__'
logging.info(endpoints.users_id_token._get_token(None))
# '__TOKEN__'
instance.put()
return instance
This works fine, I receive authorization token and user is created in datastore, but I can't figure out how to get the profile info. If I enter the token in OAuth2 API (through API Explorer):
POST https://www.googleapis.com/oauth2/v2/tokeninfo?access_token=__TOKEN__
I get token info with some data I need { "user_id": "__ID__", "verified_email": true, ...}, and if I use user_id in +API:
GET https://www.googleapis.com/plus/v1/people/__ID__
I can get the rest of the data I need (name, image, etc).
What do I need to do to achieve this in my UserRegister() method? I'd prefer to return just entity ID and do the rest of registration asynchronously, but that's another issue, I'll figure it out (; Just need some guidance how to call other endpoints from my code...
EDIT:
I've managed to figure out how to call other APIs (code on Gist), now only have one issue with Plus API:
I did some queries and eventually got anonymous quota error. Then I added key parameter and set it to WEB_CLIENT_ID or SERVICE_ACCOUNT:
WEB_CLIENT_ID is OAuth2 Client ID (type: Web Application) from console.developers.google.com/apis/credentials,
SERVICE_ACCOUNT is default App Engine service account - MY_APP#appspot.gserviceaccount.com...
and now I'm getting following error:
HttpError: <HttpError 400 when requesting https://www.googleapis.com/plus/v1/people/__VALID_USER_ID__?key=__WEB_CLIENT_ID__or__SERVICE_ACCOUNT__&alt=json returned "Bad Request">
When I use +API explorer I get results as expected:
REQUEST:
https://www.googleapis.com/plus/v1/people/__VALID_USER_ID__?key={YOUR_API_KEY}
RESPONSE:
200 OK + json data for user...
Anyone knows why is this happening?
Why am I getting BadRequest response?
Problem with BadRequest was that I didn't send authorization token... I did try to send it as access_token, but seams like +api docs are outdated - it should be oauth_token. When I included this parameter issue was resolved:
build('plus', 'v1').people().get(userId=user_id, key=SERVICE_ACCOUNT, oauth_token=token).execute()
HINT: Use http://localhost:8001/_ah/api/discovery/v1/apis/, and discoveryRestUrl property it has to see real properties of your API - this is where I found the answer.
oauth_token can be obtained like this:
token = os.getenv('HTTP_AUTHORIZATION').split(" ")[1]
# or like in my question:
token = endpoints.users_id_token._get_token(None)
I'd suggest HTTP_AUTHORIZATION variable, because users_id_token docs state that it's a:
Utility library for reading user information from an id_token.
This is an experimental library that can temporarily be used to extract
a user from an id_token. The functionality provided by this library
will be provided elsewhere in the future.
How to call other API Endpoints?
This is also an answer to my first question:
from googleapiclient.discovery import build
service = build('plus', 'v1')
request = service.people().get(userId=user_id, key=SERVICE_ACCOUNT, oauth_token=token)
response = request.execute()
data = dict(self.response.POST)
Code that worked for me is here.
NOTE: WEB_CLIENT_ID obtained from https://console.developers.google.com/apis/credentials (OAuth2 Client ID of type Web Application) will NOT work in this case. I had to use SERVICE_ACCOUNT - I didn't try to generate one through console, default service account I got from App Engine worked fine.
...things are much clearer now that I got this working. Hope it will help someone else (;

Categories