I am trying to request an authorization code as documented here.
I am using Python requests package to do this and have the following example code:
import requests
auth_endpoint = 'https://login.microsoftonline.com/%s/oauth2/authorize?api-version=1.0' % TENANT_ID
payload = {
'client_id': CLIENT_ID,
'response_type': 'code',
'resource': APP_ID_URI,
'redirect_uri': REPLY_URL
}
response = requests.get(url=auth_endpoint, data=payload)
However, when I run the code above, I get back HTML in the body and not the response I'm expecting. It seems like the HTML code is for a login page.
When I take the formatted endpoint URI and plug it into a browser, I am able to get the auth code from the redirect URI. But, is there a way to get this from the body of the response while still using the requests package?
Please use session class of requests module to implement your requirement. Please refer to the following code sample:
import requests
s = requests.Session()
USERNAME = '<username_email>'
PASSWORD = '<userpassword>'
s.auth = (USERNAME, PASSWORD)
TENANT_ID = '<tenant_id>'
# Authorize URL
authorize_url = 'https://login.microsoftonline.com/%s/oauth2/authorize' % TENANT_ID
# Token endpoint.
token_url = 'https://login.microsoftonline.com/%s/oauth2/token' % TENANT_ID
payload = { 'response_type': 'code',
'client_id': '<tenant_id>',
'redirect_uri': 'http://localhost',
'authority' :'authority'
}
response = s.get(authorize_url, params=payload ,allow_redirects=True)
print response
print response.url
Any further concern, please feel free to let me know.
Related
Question in short: how to get Facebook API access_token with permission
I want to read the reach for specific ad settings from the Facebook API using Python. In order to do so, I need a facebook access token with extended permissions. I use the following function to get a new access token, but the token I get does not have the proper permission levels. So: how to get an access_token with custom permissions, like you can do manually here?
Python example below (problem is actually language independent):
import requests
import json
from facebookads.adobjects.adaccount import AdAccount
from facebookads.api import FacebookAdsApi
from facebookads.adobjects.adset import AdSet
app_id = 'xxxx'
app_secret = 'xxxx'
account_id = 'xxxx'
def get_fb_token(app_id, app_secret):
payload = {'grant_type': 'client_credentials',
'client_id': app_id,
'client_secret': app_secret,
}
file = requests.post('https://graph.facebook.com/oauth/access_token?', params = payload)
string = file.content.decode('utf-8')
json_obj = json.loads(string)
return json_obj['access_token']
access_token = get_fb_token(app_id, app_secret)
account = AdAccount(account_id)
# initiate API
FacebookAdsApi.init(app_id, app_secret, access_token)
# Request reach
targeting_spec = {
'geo_locations': {
'countries': ['nl']
},
}
fb_params = {
'currency': 'EUR',
'optimize_for': AdSet.OptimizationGoal.offsite_conversions,
'targeting_spec': targeting_spec,
}
reach_estimate = account.get_reach_estimate(params=fb_params)
And the error message I get:
(#278) Reading advertisements requires an access token with the extended permission ads_read
Help is highly appreciated!
Try this:
payload = {
'grant_type': 'client_credentials',
'client_id': app_id,
'client_secret': app_secret,
'scope': 'ads_read'
}
file = requests.post('https://graph.facebook.com/oauth/access_token?', params = payload)
Also, you need to redirect to the correct endpoint (https://www.facebook.com/v2.xy/dialog/oauth), not POST to it. You cannot get a User token without user interaction.
I am writing a command line script accessing LinkedIN API via Library but having issues with it. Here is my code:
from linkedin import linkedin
import requests
RETURN_URL = "http://localhost"
authentication = linkedin.LinkedInAuthentication(CLIENT_ID, CLIENT_SECRET, RETURN_URL,
linkedin.PERMISSIONS.enums.values())
print(authentication.authorization_url)
get_code = authentication.authorization_url
application = linkedin.LinkedInApplication(authentication)
authentication.authorization_code = 'AQQfHou58eyVEJmbabHk1njdl-AY0bqfDjkZeosAn6DR-DiTnH7raJoDcign2U3w5w1YieYU4cjfTz3Ab-wa7cm3KwwctjzU-SoAWchjj_odArFM7q1W1CCU_15Q7gLDRrZoMCo5ivXnkisR5gYfGS0V2E_jsQ&state=74abc361c20313f5bc87d43f42f88b53#!'
# authentication.get_access_token()
data = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'authorization_code',
'redirect_uri': RETURN_URL,
'code': 'AQTqmP0g4PWGJpNnSysqvH4TCXTusoWsjbx1f3R7TPazYP4pCB81a4FrRJRUNjeJzH5yoN2XTrIT4YO-mu2VBQkhL12kwJZ09Xm_WHh97nyok0tqKHh8k54c3dCc075hrsJ8KYw02X-2XSMD-TkxQWKrUXPsMw&state=82d8d2bbbc80ba485812d2fe500cf3e9#!'
}
url = 'https://www.linkedin.com/uas/oauth2/accessToken'
r = requests.post(url, data=data)
print(r.text)
The error I get:
https://www.linkedin.com/uas/oauth2/authorization?client_id=862ztaa9740mst&redirect_uri=http%3A//localhost&scope=rw_company_admin%20r_emailaddress%20r_basicprofile%20w_share&response_type=code&state=d8e7aaefdbd32211fb7d342b238a84dc
{"error_description":"missing required parameters, includes an invalid parameter value, parameter more than once. : Unable to retrieve access token : appId or redirect uri does not match authorization code or authorization code expired","error":"invalid_request"}
Also, how to get code part dynamically?
I'm trying to make an app that makes requests to Dynamics CRM Web API from python using urllib2.
So far I can login an user with an Azure application by making a post request to https://login.microsoftonline.com/common/oauth2/authorize
then with the retrieved authorization_code I can get the access_token, refresh_token and others with urllib2
url = 'https://login.microsoftonline.com/common/oauth2/token'
post_fields = {'grant_type': 'authorization_code',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI,
'resource': 'https://graph.microsoft.com',
'code': code}
request = Request(url, urlencode(post_fields).encode())
resp = urlopen(request).read().decode()
resp = json.loads(resp)
refresh_token = resp['refresh_token']
id_token = resp['id_token']
id_token = jwt.decode(id_token,verify=False)
access_token = resp['access_token']
Then I tried to make another post request by using the access_token but had no luck.
I keep getting:
HTTP Error 401: Unauthorized
Just as a test I make a post directly to .dynamics.com/api/data/v8.1/leads
as follows:
url = 'https://<company_uri>.dynamics.com/api/data/v8.1/leads'
post_fields = {"name": "Sample Account",
"creditonhold": "false",
"address1_latitude": 47.639583,
"description": "This is the description of the sample account",
"revenue": 5000000,
"accountcategorycode": 1
}
request = Request(url, urlencode(post_fields).encode())
request.add_header('Authorization', 'Bearer ' + access_token )
request.add_header("Content-Type", "application/json; charset=utf-8")
request.add_header('OData-MaxVersion','4.0')
request.add_header('OData-Version','4.0')
request.add_header('Accept','application/json')
resp = urlopen(request).read().decode()
But i keep getting the same 401 error code.
I've looked all over msdn documentation but didn't find the way to do this directly without using any library, I just want to use a simple post request.
Since the error code says Unauthorized I think the access_token must be sent in some other way.
Can someone help me on how to correctly use the access_token on Dynamics CRM?
Thanks!
The access token you got back is for the Azure AD Graph API. Not Dynamics CRM.
To call that, you must ask for an access token with resource set to Dynamics CRM API's App ID URI, not https://graph.windows.net.
According to documentation you should set resource to https://<company_uri>.crm.dynamics.com.
So when you are retrieving token:
url = 'https://login.microsoftonline.com/common/oauth2/token'
post_fields = {'grant_type': 'authorization_code',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI,
'resource': 'https://<company_uri>.crm.dynamics.com',
'code': code}
I am learning Python and I am trying to create a playlist using the Spotify web api but get a http 400 error: Error parsing json. I guess it has to do with an incorrect variable type in the token but I am having a really hard time debugging it as I can't figure out a way to see the post request in raw format.
Posting through the API requires authorizing and this is the script I've created for that:
import requests
import base64
requests.packages.urllib3.disable_warnings()
client_id = 'ID'
client_secret = 'SECRET'
redirect_uri = 'http://spotify.com/'
scope = 'playlist-modify-private playlist-read-private'
def request_token():
# 1. Your application requests authorization
auth_url = 'https://accounts.spotify.com/authorize'
payload = {'client_id': client_id, 'response_type':'code','redirect_uri':redirect_uri}
auth = requests.get(auth_url,params = payload)
print '\nPlease go to this url to authorize ', auth.url
# 2. The user is asked to authorize access within the scopes
# 3. The user is redirected back to your specified URI
resp_url = raw_input('\nThen please copy-paste the url you where redirected to: ')
resp_code= resp_url.split("?code=")[1].split("&")[0]
# 4. Your application requests refresh and access tokens
token_url = 'https://accounts.spotify.com/api/token'
payload = {'redirect_uri': redirect_uri,'code': resp_code, 'grant_type': 'authorization_code','scope':scope}
auth_header = base64.b64encode(client_id + ':' + client_secret)
headers = {'Authorization': 'Basic %s' % auth_header}
req = requests.post(token_url, data=payload, headers=headers, verify=True)
response = req.json()
return response
This is the function actually trying to create the playlist using the authorization token (import authorizer is the function above):
import requests
import authorizer
def create_playlist(username, list_name):
token = authorizer.request_token()
access_token = token['access_token']
auth_header = {'Authorization': 'Bearer {token}'.format(token=access_token), 'Content-Type': 'application/json'}
api_url = 'https://api.spotify.com/v1/users/%s/playlists' % username
payload = {'name': list_name, 'public': 'false'}
r = requests.post(api_url, params=payload, headers=auth_header)
But whatever I try it only leads to a 400 error. Can anyone please point out my error here?
Solved by adding a json.dumps for the input: json.dumps(payload) and changing the payload to be 'data' and not 'params' in the request.
So the new functioning request equals:
r = requests.post(api_url, data=json.dumps(payload), headers=auth_header)
I am looking on how to use an APIs, more specifically Egnyte's API.
From their documentation, I must first get a oauth2 token, which I was able to get successfully.
Here are their documentation:
https://developers.egnyte.com/docs/read/Getting_Started
https://developers.egnyte.com/docs/User_Management_API_Documentation#Get-User-List
However, I am not sure what to do afterwards. I am trying to use their User management API, which I am suppose to make a call to:
https://{Egnyte Domain}.egnyte.com/pubapi/v2/users
However, how do i use their token for a requests.get call to their api?
Below is my python code, I am using the the Requests Module (http://docs.python-requests.org/en/latest/):
import requests
api_key = 'MY_API_KEY'
username = 'myUserName'
password = 'myPassword'
payload = {
'grant_type': 'password',
'client_id': api_key,
'username': username,
'password': password
}
token = requests.post("https://{Egnyte Domain}.egnyte.com/puboauth/token", params = payload)
print r.text
The response I get is:
{"access_token":"*MYToken","token_type":"bearer","expires_in":-1}
Thanks!
Ah, someone had showed me.
had to do minor adjustments to the script:
r = requests.post("https://{Egnyte Domain}.egnyte.com/puboauth/token", params=payload)
token = r.json()['access_token']
users = requests.get(url, headers={'Authorization': 'Bearer %s' % token})
You need to use the token in the authorization header of requests. The best thing would be to create a persistent connection.
r = requests.post("https://{Egnyte Domain}.egnyte.com/puboauth/token", params=payload)
if r.ok:
access_token = r.json()['access_token']
session = requests.Session()
session.headers['Authorization'] = "Bearer %s" % access_token
users = session.get('https://{Egnyte Domain}.egnyte.com/pubapi/v2/users')
OR
headers = {"Authorization":"Bearer %s" % access_token}
requests.get('https://{Egnyte Domain}.egnyte.com/pubapi/v2/users', headers=headers)