I have tried this to update my access token
import urllib
endpoint='https://accounts.google.com/o/oauth2/token'
data={'client_id':'25********15-6*********************7f.apps.googleusercontent.com','client_secret':'4********Pj-K*****x4aM','refresh_token':'1/tP************************O_XclU','grant_type':'refresh_token'}
encodedData=urllib.urlencode(data)
from httplib2 import Http
h = Http()
resp, content = h.request(endpoint, "POST", encodedData)
But got the error message
'{\n "error" : "invalid_request",\n "error_description" : "Required parameter is missing: grant_type"\n}'
You should specify the headers in your request like this:
resp, content = h.request(uri=endpoint,
method="POST",
body=encodedData,
headers={'Content-type': 'application/x-www-form-urlencoded'})
old-refresh_token is the refresh token you have
CLIENT_ID,CLIENT_SECRET are the credentials you can find those in google developers console
http = httplib2.Http()
TOKEN_URL = "https://accounts.google.com/o/oauth2/token"
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
parameters = urllib.urlencode({'refresh_token': old-refresh_token, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'grant_type': 'refresh_token'})
resp, response_token = http.request(TOKEN_URL, method='POST', body=parameters, headers=headers)
token_data = json.loads(response_token)
access_token = token_data['access_token']
the variable access_token now holds your access token
try it out
Related
From POSTMAN Code Snippet.
import requests
url = "https://www.XXXX.com/systems/num/config"
payload='{body}'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'OAuth realm="https%3A%2F%2Fwww.app-api.ing.XXXX.com%2Fsystems%2Fnum%2FXXX",oauth_consumer_key="XXXXXX",oauth_token="XXXXXX",oauth_signature_method="HMAC-SHA1",oauth_timestamp="TTTTTT",oauth_nonce="NNNNNN",oauth_version="1.0",oauth_signature="tick80j6BYSDMTw8eo%2Fp9EjoxBA%3D"'
}
response = requests.request("POST", url, headers=headers, data=payload)
Works fine in POSTMAN.
Unable to sign the XML Body and send POST Request along with realm to external API from Lambda.
My Code:
rn = nonce
client = oauthlib.oauth1.Client(consumer_key, consumer_secret, access_token, token_secret, nonce=str(rn))
uri, headers, body = client.sign(f'https://www.XXXX.com/systems/{num}/{category}')
client = oauthlib.oauth1.Client(consumer_key, client_secret=consumer_secret, resource_owner_key=access_token, resource_owner_secret=token_secret, verifier=str(rn))
uri, headers, body = client.sign(f'https://www.XXXX.com/systems/{num}/{category}',
realm=f'https%3A%2F%2FXXXX.com%2Fsystems%2F{num}%2F{category}')
payload = <XML BODY>
headers['Content-Type'] = 'application/x-www-form-urlencoded'
headers['Accept'] = 'application/x-www-form-urlencoded'
response = requests.post(uri, headers=headers, data=payload)
print(response.status_code)
Response from server:
401 Unauthorized
<error version="1.48">
<message>signature doesn't match</message>
</error>
I am trying to make a simple request to get the access token from Citrix ShareFile, but it's throwing 400 error.
I am going exactly as it's mentioned in the documentation, except changing Python2 code with HTTPLib, with Python3 code with Requests. The code is:
url = 'https://{my_domain}.sharefile.com/oauth/token'
headers = {'Content_Type': 'application/x-www-form-urlencoded'}
params = {'grant_type':'password', 'client_id':my_client_id, 'client_secret':my_client_secret, 'username':my_username, 'password':my_password}
response = requests.post(url, params=params, headers = headers)
print(response.status_code, response.reason)
I get the following response:
400 Bad Request
I also added urllib.parse.urlencode to params, but am still getting the same response error
response = requests.post(url, params=urllib.parse.urlencode(params), headers = headers)
Request guidance on what am I doing wrong. TIA
It could be the password, in the context of Sharefile it means app_password and not the password used to login to website. Or response_type to 'code'.
SF Auth is through OAuth2 with a GrandType: OAuth2 Password Grant
This way works for me:
url = 'https://{my_domain}.sharefile.com/oauth/token'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = {
'response_type': 'code',
'grant_type': 'password',
'client_id': '<YOUR CLIENT ID>',
'client_secret': '<YOUR SECRET>',
'username': '<USERNAME>',
'password': '<APP_PASSWORD>' # not regular password to login using web
}
response = requests.post(url, data=data, headers=headers)
Response contains token and refresh token.
When I add content-type my issue solved.
Check and add valid content-type
I am trying to send a push notification from Firebase Cloud Message via AWS Lambda. The API responds with authorization error.
import requests
import json
def lambda_handler(event, context):
message = event['Message']
tokens = event['PushNotificationTokens']
for token in tokens:
data = {"notification": { "title": "My Awesome App", "body": message,}, "to": token}
data_json = json.dumps(data)
print(data_json)
headers = {'Content-type': 'application/json', 'Authorization':'AAAA…...0HuQH'}
url = 'https://fcm.googleapis.com/fcm/send'
response = requests.post(url, data=data_json, headers=headers)
jsonResponse = json.loads(response.content)
print(jsonResponse)
return jsonResponse
Everything is perfect - except the headers. You'll have to add 'Key=' before the actual key. See the code below :
headers = {'Content-type': 'application/json', 'Authorization':'Key=AAAA…...0HuQH'}
So i'm writing a program that post's data to a url and get's the response. In postman it requires a token. So when I tried to make it in python it's giving me a response [401].
The problem I have is trying to get the token first and then passing it to my post_data method.
I'm going to put *** by the URL and username and password for privacy concerns.
import requests
import json
import pprint
import urllib
def get_token():
tokenurl='***'
data={
'grant_type':'password',
'username':'***',
'password':'***'
}
token=requests.post(tokenurl,data=data)
print(token)
get_token()
def post_data():
url1='***'
data={"***"
}
data_json = json.dumps(data)
headers = {'Content-type': 'application/json'}
response = requests.post(url, data=data_json, headers=headers)
pprint.pprint(response.json())
In the post_data() function, you can add your generated token to the headers
headers = {'Content-type': 'application/json','Authorization': 'token ***'}
*** is your generated token
i am trying to call my jwt authenticated django api that lives on an EC2 instance from my home laptop. the API will return me a auth key but when i try to use the auth key it tells me im not authorized. I have provided an example of the various methods i have tried to use to get this to work.
is there anything specifically i am doing wrong in this code that would warrant my code to consistently return 401 error? when asking for an authenticated API with a JWT token is there anything specifically i need to do or a specific way i need to set my headers so that i can get a value to return? or does this look like an issue with the backend?
import requests
from urllib2 import Request, urlopen
import jwt
from requests_jwt import JWTAuth, payload_method
import json
def tryme(chats, payload, jwt):
#method1
res = requests.post(chats, json=payload)
print res.status_code
# error 401
# method2
req = requests.get(chats, params=payload)
print req.status_code
# error 401
# method3
req = Request(chats)
req.add_header('Authorization', 'Token token={}'.format(auth['token']))
req.add_header('content-type', 'application/json')
res = urlopen(req)
print res.status_code
# error 401
#method4
token = JWTAuth(jwt['token'])
out = requests.get(chats, auth=token)
print out.status_code
# error 401
out = requests.post(chats, auth=token)
print out.status_code
# error 401
def main():
payload = {
'username': 'testuser',
'password': 'test1234'
}
base_url = 'https://www.example.com/api/v1/'
api_auth = base_url + 'api-token-auth/'
chats = base_url + 'chats/'
auth = json.loads(requests.post(api_auth, json=payload).content)
# returns auth token
payload = {'Authorization': 'Token {}'.format(auth['token']), 'content-type': 'application/json'}
tryme(chats, payload, auth)
payload = {'Authorization': 'Bearer {}'.format(auth['token']), 'content-type': 'application/json'}
tryme(chats, payload, auth)
payload = {'Authorization': 'JWT {}'.format(auth['token']), 'content-type': 'application/json'}
tryme(chats, payload, auth)
if __name__ == '__main__':
main()
this was solved. however i upgraded to python3.
import requests
import urllib3
urllib3.disable_warnings()
payload = {
'username': 'testuser',
'password': 'test1234'
}
base_url = 'https://www.example.com/api/v1/'
api_auth = base_url + 'api-token-auth/'
chats = base_url + 'chats/'
# get jwt token from login credentials
auth = json.loads(requests.post(api_auth, json=payload).content)['token']
# correctly format the call which was my primary issue above.
payload = {'Authorization': 'JWT {}'.format(auth)}
# in python3 use urllib3.
http = urllib3.PoolManager()
res = http.request('GET', chats, headers=payload)
print(res.data)
in python2:
import requests
payload = {
'username': 'testuser',
'password': 'test1234'
}
base_url = 'https://www.example.com/api/v1/'
api_auth = base_url + 'api-token-auth/'
chats = base_url + 'chats/'
# get jwt token from login credentials
auth = json.loads(requests.post(api_auth, json=payload).content)['token']
# correctly format the call which was my primary issue above.
payload = {'Authorization': 'JWT {}'.format(auth)}
# make sure you are using the right request (GET vs POST)
out = requests.get(chats, headers=token)
print out.content