So I have been using powershell for quite a while now and am somewhat familiar with getting a token from an Azure application using MS Graph configured with application API permissions. I am now attempting to perform the same in a python console application and am getting flummoxed as I constantly get a 400 error. here's the snippet of my code...
import requests
import json
app_id='<appid>'
client_secret='<client secret>'
token_url='https://login.microsoftonline.com/<tenant id>/oauth2 /v2.0/token'
token_data = {
'grant_type': 'client_credentials',
'client_id': app_id,
'client_secret': client_secret,
'resource': 'https://graph.microsoft.com',
'scope':'https://graph.microsoft.com/.default'
}
headers = {'content-type':'application/json'}
token_r = requests.post(token_url, json=token_data)
token = token_r.json().get('access_token')
any ideas?
Figured it out. I needed to add the oAuth2 requests library. See sample code below:
import requests
import json
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
app_id='<app id>'
client_secret='<client Secret>'
token_url='https://login.microsoftonline.com/tennantname.onmicrosoft.com/oauth2/v2.0/token'
scope='https://graph.microsoft.com/.default'
client = BackendApplicationClient(client_id=app_id, scope=scope, grant_type="client_credentials")
session = OAuth2Session(client=client, scope=scope)
# fill access token
token = session.fetch_token(token_url=token_url,client_id=app_id,scope=scope,client_secret=client_secret)
Related
I am trying to use the OAuth2 module to connect with the CG Trader API (https://api.cgtrader.com/docs/overview.html), however I keep on getting the codes [200] and [422] from the terminal. This is my code so far:
from wsgiref import headers
from requests import request
import requests
import json
SPACE = " "
CLIENT_ID ="couldn't show it for privacy reasons"
CLIENT_SECRET = "couldn't show it for privacy reasons"
REDIRECT_URL = "127.0.0.1"
ACCESS_TOKEN_URL = "https://www.cgtrader.com/oauth/applications/213"
headers ={
"grant_type": "authorization_code",
"scope": "oapi",
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"redirect_url": REDIRECT_URL,
}
response_get = ("{}?response_type=code&client_id={}&redirect_url={}".format(ACCESS_TOKEN_URL, CLIENT_ID, REDIRECT_URL))
response_post = requests.get(response_get, headers)
response_post1 = requests.post(response_get, headers)
#print(response_get.json)
print(response_post.json)
print(response_post1.json)
I do not want to use rauth as that would require people to run my addon as administrator which I would prefer not to be the case.
Can anyone help me figure out this issue? This is crucial for my project.
I have a problem working with python-quickbooks package, I try to follow the docs: https://pypi.org/project/python-quickbooks/
Here is my code:
from django.conf import settings
from intuitlib.client import AuthClient
from quickbooks import QuickBooks
from quickbooks.objects.account import Account
auth_client = AuthClient(
client_id=settings.QUICKBOOKS_CLIENT_ID,
client_secret=settings.QUICKBOOKS_CLIENT_SECRET,
environment='sandbox',
redirect_uri=settings.QUICKBOOKS_REDIRECT_URI,
)
client = QuickBooks(
auth_client=auth_client,
refresh_token=settings.QUICKBOOKS_REFRESH_TOKEN,
company_id=settings.QUICKBOOKS_REALM_ID
)
account = Account()
account.from_json(
{
"AccountType": "Accounts Receivable",
"Name": "MyJobs"
}
)
account.save(qb=client)
However, this results in error:
What am I doing wrong here?
You have to provide ACCESS_TOKEN in AuthClient.
In order to get an access token, you have to pass authorization. You can check details about the authorization process here https://developer.intuit.com/app/developer/qbo/docs/develop/authentication-and-authorization/oauth-2.0-playground
Also here is a repo with an example of how to use AuthClient: https://github.com/IntuitDeveloper/SampleOAuth2_UsingPythonClient
from intuitlib.client import AuthClient
from quickbooks.client import QuickBooks, Environments
auth_client = AuthClient(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL, Environments.SANDBOX, ACCESS_TOKEN)
qbo_client = QuickBooks(
auth_client=auth_client,
refresh_token=REFRESH_TOKEN,
company_id=REALM_ID,
)
from oauthlib.oauth2 import BackendApplicationClient
from requests.auth import HTTPBasicAuth
from requests_oauthlib import OAuth2Session
import requests
client_id = *CLIENT_ID*
client_secret = *CLIENT_SECRET*
auth = HTTPBasicAuth(client_id, client_secret)
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token =oauth.fetch_token(token_url='https://login.microsoftonline.com/*TENANT_ID*/oauth2/token', auth=auth,resource= 'https://management.azure.com/')
data = {'Content-Type':'application/json',
'Authorization': 'Bearer ' + token['access_token']}
r =requests.post('https://management.azure.com/subscriptions/'
'*SUBSCRIPTION_ID*/providers/Microsoft.Compute/'
'locations/eastus/vmSizes?api-version=2016-04-30-preview', headers=data)
I'm trying to get list of available VM's, but I'm getting an error:
{'error': {'code': 'AuthorizationFailed', 'message': "The client 'X' with object id 'X' does not have authorization to perform action 'Microsoft.Compute/locations/vmSizes/read' over scope '/subscriptions/Y'."}}
Firstly, the api you used method is get not post.
Secondly, you need give your sp Owner role, according to the error log, you don't give enough permission to your service principal, please see this link:assign-application-to-role.
I test in my lab, the following code works for me.
from oauthlib.oauth2 import BackendApplicationClient
from requests.auth import HTTPBasicAuth
from requests_oauthlib import OAuth2Session
import requests
client_id = ''
client_secret = ''
auth = HTTPBasicAuth(client_id, client_secret)
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token =oauth.fetch_token(token_url='https://login.microsoftonline.com/<tennat id>/oauth2/token', auth=auth,resource= 'https://management.azure.com/')
data = {'Content-Type':'application/json',
'Authorization': 'Bearer ' + token['access_token']}
r =requests.get('https://management.azure.com/subscriptions/<subscription id>/providers/Microsoft.Compute/locations/eastus/vmSizes?api-version=2016-04-30-preview', headers=data)
for i in r:
print i
When trying to authorize spotify using python 3, I get a "server_error" with the description "Unexpected status: 400".
I am using the correct authorization code and the spotify documentation (https://developer.spotify.com/web-api/authorization-guide/) instructed me to use a post command with those parameters.
I'm quite a noob in this and I do not know what I am doing wrong.
Here is the code:
import requests
params = {'grant_type': 'authorization_code', 'code': authcode, 'redirect_uri': 'https://example.com/callback','client_id':'example', 'client_secret':'example'}
req=requests.post('https://accounts.spotify.com/api/token', params=params)
print(req.content)
According to spotify's own guide (see step #4):
https://developer.spotify.com/web-api/authorization-guide/
The authorization info for requesting a new token must go in the header via an "Authorization" variable:
Authorization: Required. Base 64 encoded string that contains the
client ID and client secret key. The field must have the format:
Authorization: Basic base64 encoded client_id:client_secret
You have it instead in the request body itself.
So you should do something like:
import requests
import base64
authcode = 'valid_authcode_from_prev_authorization_step'
params = {'grant_type': 'authorization_code', 'code': authcode, 'redirect_uri': 'https://example.com/callback'}
client_id = 'example_id'
client_secret = 'example_secret'
b64_val = base64.b64encode("%s:%s" % (client_id, client_secret))
req = requests.post(
'https://accounts.spotify.com/api/token', params=params,
headers={'Authorization': b64_val})
However, for this to work you need a valid auth code which you can only get by having the user go through the auth step which precedes the token acquisition step.
This code gets sent to the callback you have registered in your app settings, which won't work if you have a fake callback set (ie: http://example.com/callback).
I am trying to use OAuth2 to get an authorization token using Python to a REST API. I am successful doing so using CURL but not with python. I am using the examples provided at the following docs:
https://requests-oauthlib.readthedocs.org/en/latest/oauth2_workflow.html
The following is my code:
#!/usr/bin/python
import requests
import requests_oauthlib
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
client_id = 'AAAAAA'
client_secret = 'BBBBBB'
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url='https://example.com/as/token.oauth2', client_id=client_id, client_secret=client_secret)
print token
I am getting the following error:
oauthlib.oauth2.rfc6749.errors.InvalidClientError: (invalid_client) client_id value doesn't match HTTP Basic username value
This is a very basic API that only needs client_id and client_credentials to get an authorization token.
All information would be greatly appreciated.
The documentation specifies the following items:
client_id = r'your_client_id'
client_secret = r'your_client_secret'
redirect_uri = 'https://your.callback/uri'
By client key do you perhaps mean client key?
token = oauth.fetch_token(token_url='https://example.com/as/token.oauth2', client_id=client_id, client_secret=client_secret)
Try changing it to the above and give it a spin. using r'' for raw input instead and the token given.
I have found myself in a similar circumstance.
I am writing a Django app.
I was getting unauthorized_client and invalid_client exceptions.
In my case the post request in "Exchange the code" ("step 3" in the OAuth2 protocol) wasn't being formulated correctly.
Through much searching and trial and error I found it is possible to essentially customise the request. You can do this by specifying the optional arguments of auth, header and/or body.
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import WebApplicationClient, BackendApplicationClient
from requests.auth import HTTPBasicAuth
client_id = CLIENT_ID
client_secret = CLIENT_SECRET
authorization_base_url = AUTHORIZE_URI
token_url = TOKEN_URI
redirect_uri = REDIRECT_URI
auth = HTTPBasicAuth(client_id, client_secret)
scope = SCOPE
# Create the Authorization URI
# Not included here but store the state in a safe place for later
the_first_session = OAuth2Session(client_id=client_id, redirect_uri=redirect_uri, scope=scope)
authorization_url, state = the_first_session.authorization_url(authorization_base_url)
# Browse to the Authorization URI
# Login and Auth with the OAuth provider
# Now to respond to the callback
the_second_session = OAuth2Session(client_id, state=state)
body = 'grant_type=authorization_code&code=%s&redirect_uri=%s&scope=%s' % (request.GET.get('code'), redirect_uri, scope)
token = the_second_session.fetch_token(token_url, code=request.GET.get('code'), auth=auth, body=body)