I'm trying to use OAuth2 authorization for an API through the company Manheim using Python 3.
The documentation states "The 'Client Credentials' and 'Resource Owner' grant types are both supported now and required changes to request a token are detailed here." Here is the documentation to the API: http://developer.manheim.com/#/authentication
I've used the following link as a guide but to no avail:
https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow
They've provided me with a client id and client secret. I'm receiving the following error:
MissingTokenError: (missing_token) Missing access token parameter.
I've tried this:
from oauthlib.oauth2 import BackendApplicationClient
client_id = 'my_id'
client_secret = 'my_secret'
token_url = 'https://sandbox.api.manheim.com/oauth2/token.oauth2'
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=token_url,
client_id=client_id,client_secret=client_secret)
I've also tried this:
from oauthlib.oauth2 import BackendApplicationClient
from requests.auth import HTTPBasicAuth
client_id = 'my_id'
client_secret = 'my_secret'
token_url = 'https://sandbox.api.manheim.com/oauth2/token.oauth2'
auth = HTTPBasicAuth(client_id, client_secret)
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=token_url, auth=auth)
I've tried other techniques but have had no success. What am I doing wrong? What do I need to do access the API?
I appreciate any and all help!
RESULT:
Fixed it myself by reaching out to the developer team managing the API. I was using the wrong endpoint.
I changed token_url to the following:
token_url = 'https://api.manheim.com/oauth2/token.oauth2'
Related
i'm trying to get user data from AAD using Microsoft Graph API Python SDK.
App registration that i have in company tenant has the followiing API permissions:
I'm using the following piece of code to get user's details from AAD:
from azure.common.credentials import ServicePrincipalCredentials
from azure.graphrbac import GraphRbacManagementClient
credentials = ServicePrincipalCredentials(
client_id="appClientId",
secret="appClientSecret",
resource="https://graph.windows.net",
tenant = 'companyTenant'
)
tenant_id = 'companyTenantId'
graphrbac_client = GraphRbacManagementClient(
credentials,
tenant_id
)
user = graphrbac_client.users.get("myUserObjectId")
And get "azure.graphrbac.models.graph_error_py3.GraphErrorException: Insufficient privileges to complete the operation."
I'm using Python 3.10.5 and my app service should be able to get data of any user from AAD.
What am i doing wrong here?
Looks like the resource are trying to reach out is incorrect , https://graph.windows.net is used when you want to connect to AAD graph , please check the docs for more info - https://learn.microsoft.com/en-us/previous-versions/azure/ad/graph/howto/azure-ad-graph-api-operations-overview.
Could you please try by using the resource = graph.microsoft.com .
graph.microsoft.com is correct endpoint for graph .
please see the doc - https://learn.microsoft.com/en-us/graph/use-the-api
Hope this helps
Thanks
I tried to reproduce the same in my environment and got below results:
I created one Azure AD application and granted API permissions like below:
When I ran the same code as you, I got same error as below:
from azure.common.credentials import ServicePrincipalCredentials
from azure.graphrbac import GraphRbacManagementClient
credentials = ServicePrincipalCredentials(
client_id="appClientId",
secret="appClientSecret",
resource="https://graph.windows.net",
tenant = 'companyTenantId'
)
tenant_id = 'companyTenantId'
graphrbac_client = GraphRbacManagementClient(
credentials,
tenant_id
)
user = graphrbac_client.users.get("myUserObjectId")
Response:
I agree with Vicky kumar that graph.windows.net is deprecated and you need to change/migrate to https://graph.microsoft.com.
But the libraries that you are using won't support this resource that results error as below:
Your current library azure.graphrbac only supports resource as graph.windows.net that needs AAD graph permissions:
To resolve the error, you can make use of below code by installing urllib3 library beforehand:
import urllib3
uri = "https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token"
payload= {
'Content-Type': 'application/x-www-form-urlencoded',
'Host': 'login.microsoftonline.com',
'client_id': '3de439c4-570d-4534-bxxb-e3axxx5d', #Your AppID
'scope': 'https://graph.microsoft.com/.default',
'client_secret': 'T2Y8Q~wYQxxxxxxxxxxOODUtFxajo', #Your client secret
'grant_type': 'client_credentials'
}
http = urllib3.PoolManager()
response = http.request('POST', uri, payload)
my_dict = eval(response.data)
token = f"{my_dict['token_type']} {my_dict['access_token']}"
#print(token)
uri5 = 'https://graph.microsoft.com/v1.0/users/myUserID'
payload5 = {'Authorization':token,'Host':'graph.microsoft.com','ConsistencyLevel':'eventual'}
https = urllib3.PoolManager()
response5 = http.request('GET', uri5, headers=payload5)
print(response5.data)
When I ran the above code, I got the user details successfully as below:
Okay, so it came out that the issue was that i was using wrong SDK, the one that i've used was working with the AAD graph but i need Microsoft.Graph (if the permission that i've granted to the app registration would be of the AAD Graph type - then it would work, but since AAD Graph cannot be assigned anymore to the app registration since it is deprecated i've assigned Microsoft.Graph permission).
So the fix was to use another SDK from MS (that is currenty in preview) and it worked for me, here is the code:
from azure.identity import ClientSecretCredential
from msgraph.core import GraphClient
credential = ClientSecretCredential(tenant_id='tenantId',client_secret='appRegClientId',client_id='appRegClientSecret')
client = GraphClient(credential=credential)
result = client.get('/users') # gets all users
# result = client.get('/users/userObjectId') # gets a certain user by it's objectId
# result = client.get('/users/email') # gets a certain user by it's email address
print(result.json())
I'm new to Python and attempting to write a script that connects to RightSignature API using a private API Token. The documentation says to use the Private API Token, along with the Client ID and Client Secret to sign API requests. This should be returning information about the authenticated RightSignature User. All the private info is stored in a .env file.
Here's what I have so far...
from flask import Flask, request, jsonify
import os
import requests
from dotenv import load_dotenv
API_HOST = "api.rightsignature.com"
load_dotenv()
API_TOKEN = os.environ.get("API_TOKEN")
CLIENT_ID = os.environ.get("client_id")
CLIENT_SECRET = os.environ.get("client_secret")
headers = {
"private-api-key" : API_TOKEN,
"client-id" : CLIENT_ID,
"client-secret" :CLIENT_SECRET
}
url = "https://{}/public/v2/me".format(API_HOST)
response = requests.get(url, headers=headers)
print(response.text)
I get the following error if I run this...
{"error":"invalid_token","error_description":null}
Any help would be greatly appreciated!!!
I am currently attempting to authenticate to Azure using the azure-mgmt-support MicrosoftSupport client and am receiving the following error:
AdalError: Get Token request returned http error: 400 and server response: {"error":"unauthorized_client","error_description":"AADSTS700016: Application with identifier 'xxx' was not found in the directory 'management.core.windows.net'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.
I have double checked and am definitely using the correct client_id and tenant_id. What am I missing here? My code below:
from azure.mgmt.support import MicrosoftSupport
from msrestazure.azure_active_directory import ServicePrincipalCredentials
sub_id = 'xxx'
sp_creds = ServicePrincipalCredentials(client_id='xxx', secret='xxx')
SupportClient = MicrosoftSupport(sp_creds, sub_id)
After a short walk and another look at the documentation, and I spotted my error - I was missing the tenant_id from the ServicePrincipalCredentials object. It's not obvious from the SDK specification or error message that this is what was missing as the only required variables are client_id and secret, however when I looked at this example in the documentation I realised it was missing (pasting code below for posterity, in case docs page changes).
import os
from azure.mgmt.resource import SubscriptionClient
from azure.common.credentials import ServicePrincipalCredentials
# Retrieve the IDs and secret to use with ServicePrincipalCredentials
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]
tenant_id = os.environ["AZURE_TENANT_ID"]
client_id = os.environ["AZURE_CLIENT_ID"]
client_secret = os.environ["AZURE_CLIENT_SECRET"]
credential = ServicePrincipalCredentials(tenant=tenant_id, client_id=client_id, secret=client_secret)
subscription_client = SubscriptionClient(credential)
subscription = next(subscription_client.subscriptions.list())
print(subscription.subscription_id)
I am trying ti get user Token using Facebook oauth2 api but i am facing this error when redirect url call.
InsecureTransportError at /data/FacebookAuth/
(insecure_transport) OAuth 2 MUST utilize https.
I have running ngrok & https setup but i can't figure out why it is giving me this error
Here is my code to get this token in django
#Facebook App Credentials
client_id = 'xxxx'
client_secret = 'xxxxx'
# OAuth endpoints given in the Facebook API documentation>
authorization_base_url = 'https://www.facebook.com/dialog/oauth'
token_url = 'https://graph.facebook.com/oauth/access_token'
redirect_uri = 'https://ab207c1f.ngrok.io/data/FacebookAuthRedirect'
facebook = OAuth2Session(client_id, redirect_uri=redirect_uri)
facebook = facebook_compliance_fix(facebook)
#Getting Facebook Authentication
def FacebookAuth(request):
authorization_url, state = facebook.authorization_url(authorization_base_url)
redirect(authorization_url)
#Getting Facebook Authentication Redirect
def FacebookAuthRedirect(request):
redirect_response = request.GET.get('code', '')
token = facebook.fetch_token(token_url, client_secret=client_secret,
authorization_response=redirect_response)
print(token)
return HttpResponse('ibrahim')
After digging a bit. I found a solution that worked for me.
it was because of authorization_code = request.build_absolute_uri(). I tried printing it and it contained "http" instead of "https". I replaced the string with https using the following code.
redirect_response = redirect_response.replace("http://", "https://")
Im trying to use the youtube analytics API. I already have the access token of the channel stored in some db. In Php, you can build the client and just add the access token, client_id, client_secret then use the client to call youtube analytics.
In the python example however, I saw something like this:
flow = flow_from_clientsecrets(
CLIENT_SECRETS_FILE,
scope=' '.join(YOUTUBE_SCOPES),
message=MISSING_CLIENT_SECRETS_MESSAGE)
storage = Storage('%s-oauth2.json' % sys.argv[0])
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = run_flow(flow, storage, data)
http = credentials.authorize(httplib2.Http())
yt.analytics = build(
YOUTUBE_ANALYTICS_API_SERVICE_NAME,
YOUTUBE_ANALYTICS_API_VERSION,
http=http)
It authenticates the user using the browser. I don't need to go by that step since I already have the access_token stored in the db. The question is how to use that access_token in the build() function call so that I can proceed with the query below.
analytics_query_response = yt_analytics.reports().query(
ids='channel==',
metrics=options.metrics,
dimensions=options.dimensions,
start_date=options.start_date,
end_date=options.end_date,
max_results=options.max_results,
sort=options.sort,
).execute()
Unfortunately, the build function doesn't have an access_token parameter. Here are the docs.
You can also create your credentials object like this, though (which may be what you are looking for):
from oauth2client.client import GoogleCredentials
from oauth2client import GOOGLE_TOKEN_URI
access_token = YOUR_TOKEN
token_expiry = None
token_uri = GOOGLE_TOKEN_URI
user_agent = 'Python client library'
revoke_uri = None
credentials = GoogleCredentials(
access_token,
client_id,
client_secret,
refresh_token,
token_expiry,
token_uri,
user_agent,
revoke_uri=revoke_uri
)