unauthorized_client error when trying to impersonate an account - python

On Google Business Profile API (Google MyBusiness), I am getting following error when I try to impersonate with an email address:
('unauthorized_client: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.', {'error': 'unauthorized_client', 'error_description': 'Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.'})
I am trying to achieve this using a Python script which is using Google API Client Library:
file_location = '/some/folder/file.json'
impersonated_email = 'abc#abc.com'
scope = ["https://www.googleapis.com/auth/business.manage"]
credentials = ServiceCredentials.from_service_account_file(file_location, scopes=scope, subject=impersonated_email)
If I try to access the endpoint without using the subject parameter, it is working. But of course the main purpose here is impersonating. And the Google documentation says it is possible to impersonate with the subject parameter (or via with_subject function).
By the way, if I tried some invalid mail address, my error is changing to: ('invalid_grant: Invalid email or User ID', {'error': 'invalid_grant', 'error_description': 'Invalid email or User ID'})
So I assume that I can get the user credentials; but have no idea what could have been wrong.
Does anybody have any idea about the issue? What could be the possible issues?

Well, Google explains that JWT error code like that:
error field: unauthorized_client
error_description field: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.
Meaning:
A service account was authorized using the client email address rather than the client ID (numeric) in the Admin console.
How to resolve:
In the Domain-wide delegation page in the Admin console, remove the client, and re-add it with the numeric ID.
I tried that but I still got the error.
Then, after some digging; I saw that you only can impersonate G-Suite accounts.
So, after that I tried same code with another real-person mail which is a G-Suite account and it worked.

Related

Azure Python SDK Credential Refresh

I'm using the azure python sdk to programmatically connect to azure services via linux.
I can login successfully via az('login')
login found
However, when I try to create credentials and get a token, I get an error that my grant is expired:
creds = DefaultAzureCredential()
token = creds.get_token('https://database.windows.net/.default')
VisuaLStudioCodeCredential.get_token failed: Azure Active Directory error ' (invalid_grant) AADSTS50173: The provided grant has expired due to it being revoked, a fresh auth token is needed. The user might have changed or reset their password. The grant was issued on '2021-11-04T15:21:38,19517642' and the TokensValidFrom date (before which tokens are not valid) for this user is '2022-01-0819:52:17.0000000z'
How do I refresh this? I tried using az('account clear'), then az('login') but I get the same result. Is there a method specific for DefaultAzureCredential to get a refreshed token?
DefaultAzureCredential class tries to acquire a token using multiple methods in a particular order and VS Code logged in user has a higher precedence than Azure CLI logged in user.
When you use az login, you are logging in using Azure CLI and it seems you are already logged in into VS Code using some other credentials which does not have proper permissions and this is why you are getting this error.
To fix this issue, you can exclude VS Code credentials to be considered by setting exclude_visual_studio_code_credential to true. So your code would be something like:
creds = DefaultAzureCredential(exclude_visual_studio_code_credential=true)
That way DefaultAzureCredential will not take your VS Code credentials to acquire the token.

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.

AWS cognito access from backend

I have created a sample congnito app and added few users, now i am trying to access the users from python code , but getting below error, i have developer access. Please let me know how to get user details from cognito
code:
import boto3
client = boto3.client('cognito-idp',region_name='us-east-2')
response = client.admin_get_user(
UserPoolId='us-east-2_XXXXXXX',
Username='newuser'
)
error:ClientError: An error occurred (ExpiredTokenException) when calling the AdminGetUser operation: The security token included in the request is expired

Using AWS cognito Identity with openID salesforce in python boto3

I am doing a POC for an application that will use SSO from Salesforce using OpenID and pass the id_token to cognito user identity to get temporary credentials for s3. I have set up all the roles and services and app on AWS/Salesforce. I am able to access s3 when I enable unauthorized access for my identity. But whenever I try to pass the id_token for authenticated access it throws me this error:
botocore.errorfactory.NotAuthorizedException: An error occurred
(NotAuthorizedException) when calling the GetId operation: Invalid
login token. Issuer doesn't match providerName
I am following the tutorial here https://aws.amazon.com/blogs/security/building-an-app-using-amazon-cognito-and-an-openid-connect-identity-provider/
I am using python Boto3. This is my current code:
import boto3
id_token='aaaaaa.bbbbbbbb.cccccccc' #Got from the url salesforce sends after successful authentication
client = boto3.client('cognito-identity', 'us-east-2')
resp = client.get_id(AccountId='123456789123', IdentityPoolId='us-east-2:xxxxxxx-yyyy-zzz-hhhhh-jj888hhhh',
Logins={
'provider_url': id_token
}
)
Any help would be greatly appreciated.
Apparently the problem was the provider_url as the error suggested. I was simply putting login.salesforce.com when instead i had to change it to what the id_token was returning as their issuer id. I had to change it in the AWS access providers in IAM as well as in code.

Missing redirect_uri error for Resource owner password credentials grant type

I am trying to write a script on Python that fetches my friend list from facebook. To fetch data, I need to get the access token. I am using requests_oauthlib package to achieve the same. Since I am not writing a web application, I have not used local webserver(no redirect url). I choose to use Resource owner password credentials grant type. I am getting error.
This is my code:
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import LegacyApplicationClient
FACEBOOK_APP_ID = '**********'
FACEBOOK_APP_SECRET = '*********'
username = 'Aman Mittal'
password = '****'
token_url = "https://graph.facebook.com/oauth/access_token"
oauth = OAuth2Session(client=LegacyApplicationClient(client_id=FACEBOOK_APP_ID))
oauth_access_token = oauth.fetch_token(token_url, client_secret=FACEBOOK_APP_SECRET,username=username, password=password, client_id=FACEBOOK_APP_ID)
When I run the script, it shows error - 'Missing access token parameter'
I went through traceback and realized that access token received is this:
{"error":{"message":"Missing redirect_uri parameter.","type":"OAuthException","code":191,"fbtrace_id":"CUSmQKT8YGb"}}
First of all, I don't understand while using Legacy Application client(Resource Owner password credentials grant type ), why do I need redirect uri?
If I do choose to start a webserver alongside using web.py or something else. How do I register it on Facebook? or Do I even need to?
PS. I am new to both Python and posting on Stack Overflow. Please try to explain with details and forgive me if I have committed any stupid mistake.
Facebook does not support the OAuth 2.0 Resource Owner Password Credentials grant type.

Categories