I am trying to Share a Post on Linkedin on user's behalf.
I took the user through authentication process to generate oauth2 token. I have the token but now i am stuck how to use it. All the help i found on the internet was regarding Oauth not Oauth2. I am trying to send the request but i am getting HTTP Error 401: Unauthorized. Below is my code...
import urllib2, cookielib
cookie_jar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))
urllib2.install_opener(opener)
xml_request = ..... XML
headers={'Content-Type': 'application/xml'}
url = "http://api.linkedin.com/v1/people/~/shares/?oauth2_access_token=XXXX"
req = urllib2.Request(url, data=xml_request, headers = headers)
rsp = opener.open(req)
content = rsp.read()
I have checked and the token is valid i am getting Network Updates using the same token... I have searched and searched but still no help on Oauth2. All the Linkedin Clients i have seen in using Oauth not Oauth2..
Please help me out on how to send this request.
If anyone know any api or client which uses oauth2 please let me know..
Thanks in advance for your help
I wrote below code to Share Content on linkedin using OAuth 2.0
import requests
import json
def make_request(method, url, token ,data=None, params=None, headers=None, timeout=60):
headers = {'x-li-format': 'json', 'Content-Type': 'application/json'}
params = {}
kw = dict(data=data, params=params, headers=headers, timeout=timeout)
params.update({'oauth2_access_token': token})
return requests.request(method.upper(), url, **kw)
def submit_share(comment, title, description, submitted_url, submitted_image_url, token):
post = {
'comment': comment,
'content': {
'title': title,
'submitted-url': submitted_url,
'submitted-image-url': submitted_image_url,
'description': description
},
'visibility': {
'code': 'anyone'
}
}
url = 'https://api.linkedin.com/v1/people/~/shares'
try:
response = make_request('POST', url, token,data=json.dumps(post))
response = response.json()
return response
except Exception:
return False
I hope this code helps anyone.
Regards
Related
The following code throws a 401 error and the access_token does not get retrieved. It seems like https://www.reddit.com/api/v1/access_token is rejecting the username/password or clientID/Secretkey that I have provided. But all that info is correct, the username and password is absolutely same as the Reddit login details, and the client ID & Secret key are directly a copy-paste from a dev app created here: https://www.reddit.com/prefs/apps
Please suggest what could be wrong
import requests
auth = requests.auth.HTTPBasicAuth('<client_id>', '<client_secret>')
data = {'grant_type': 'password','username': 'username','password': 'password'}
headers = {'User-Agent': 'ApiTest/0.0.1'}
res = requests.post('https://www.reddit.com/api/v1/access_token',auth=auth, data=data, headers=headers)
if "Unauthorized" in res.text:
print('401 error occured')
TOKEN = res.json()['access_token']
headers = {**headers, **{'Authorization': f"bearer {TOKEN}"}}
requests.get('https://oauth.reddit.com/api/v1/me', headers=headers)
Try to change from bearer to Bearer in your headers. You can also remove the **.
Should be something like this:
headers = {'Authorization': f"Bearer {TOKEN}"}
i can access a API by browser requesting URL?access_token=jdjdfjhdjkdhf for example, and open a json in browser with datas, so 200 OK
The api is Oauth2.0
When i try open this same API in python, i'm receveing a 401 error, i check the readers but can't access, code below
import requests
import json
url = 'https://www.myRUL/web_api/auth' #url de obtenção token
consumer_key = 'MYCONSUMERKEY'
consumer_secret = 'MYSECRET'
code = 'MYCODE'
payload = {'consumer_key' : consumer_key,'consumer_secret' : consumer_secret,'code' : code}
response = requests.post(url, json=payload)
response = response.json()
print(response)
At this point I can receive a access_token into a json in python, with a 200OK code, so I try access data with my ne access_token
Something like that, just a example json with no real datas:
HTTP/1.1 201 OK
{
code: 201,
message: "Created tokens",
access_token: "abc96fb7b1defd2496b9a9d81071fa12319b12306465e057d0ebca9bd9ab19",
refresh_token: "bbc96fb7b1defd2496b9a9d81071fa12319b12306465e057d0ebca9bd9ab19",
date_expiration_access_token: "2016-08-12 14:35:14",
date_expiration_refresh_token: "2016-09-11 11:35:14",
date_activated: "2016-08-12 11:35:14",
store_id: "123123"
}
And than, finally when i try acceses the api with my access_token
url_orders = 'myURL/web_api/orders' #url de consulta
headers = {"Accept": "application/json"}
pay = {'access_token': response['access_token']}
print(requests.get(url_orders, json=pay))
So i receive a error 401
What I'm doing wrong
Thank you
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 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.
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)