twitter developer api oauth gives bad authentication data, but all good - python

Trying to get Twitter to authenticate my get request to the new api for recent tweets around a particular topic. I have some issues with the authentication, that I can't seem to pin down. I authenticated my application using a client key and client secret, then authenticated a user and accepted that the app can read and write permissions. With the users authentication token and secret I tried to authenticate to get the data from the newish api and got bad authentication error.
Can you see what I am doing wrong?:
curl --request GET --url 'https://api.twitter.com/2/tweets/search/recent?query=python' --header \
'authorization: OAuth \
oauth_consumer_key="i_put_api_key_here",\
oauth_consumer_secret="i_put_api_secret_here",\
oauth_token="i_put_user_token_after_accepting_app_can_make_changes",\
oauth_token_secret="i_put_oauth_token_secret", \
oauth_signature_method="HMAC-SHA1",\
oauth_timestamp="",\
oauth_version="1.0"'
return data is:
{"title":"Unauthorized","type":"about:blank","status":401,"detail":"Unauthorized"}
I'm referring to this document: https://developer.twitter.com/en/docs/authentication/oauth-1-0a
I'm pretty sure I am supplying all the data it needs correctly.

Python saved the day. You can request a bearer token from the Twitter Api dashboard for the app. Then use OAuth 2.0 like so,
def get_data(url):
headers = {'Authorization': "Bearer " + str(TWITTER_BEARER_TOKEN) }
response = requests.get(url, headers=headers)
response_data = response.json()
return response_data
get_data('https://api.twitter.com/2/tweets/search/recent?query="Python";max_results=10')
Out[20]:
{'data': [{'id': '1294146621652045826',
'text': 'RT #jacoblawherlin: #Taco_Farmer1 Maybe this is why Python is so popular for data science but not software dev (in addition to performance)…'},

Related

How can I test AWS Cognito protected APIs in Python?

I'm trying to test out some AWS APIs that are protected by Cognito. I found the first part on how to get the Json token but I can't figure out how to use the token correctly so I can authenticate on the API.
Here's my code :
import boto3 as boto3;
import requests
username='test#gmail.com'
password='test1234567'
client = boto3.client('cognito-idp')
response = client.initiate_auth(
AuthFlow='USER_PASSWORD_AUTH',
AuthParameters={
"USERNAME": username,
"PASSWORD": password,
},
ClientId='12121212121212',
)
token = response['AuthenticationResult']['AccessToken']
#print("Log in success")
#print("Access token:", response['AuthenticationResult']['AccessToken'])
#print("ID token:", response['AuthenticationResult']['IdToken'])
url = 'https://XXXXXXXX.execute-api.eu-west-1.amazonaws.com/Prod/incidents'
#print('url:', url)
#response = requests.get(url, headers={'authorization': token })
#print('GET:', response.status_code)
head = {'Authorization': token}
response = requests.get(url, headers=head)
print(response.content)
I'm getting the following error message :
b'{"message":"Authorization header requires \'Credential\' parameter. Authorization header requires \'Signature\' parameter. Authorization header requires \'SignedHeaders\' parameter. Authorization header requires existence of either a \'X-Amz-Date\' or a \'Date\' header. Authorization=
Ok so I found the problem and it's working fine now, 2 things were wrong :
The endpoint was wrong - AWS doesn't send a correct error message (!)
The request has to be sent with response['AuthenticationResult']['IdToken']
Please make sure you have selected Cognito or IAM in your API Gateway. From the error message it seems you have selected IAM for protecting the API.
Check the Authorization header's name which you configured for your Cognito Authorizer. You need to use same header name while passing the Cognito token.
If you have configured OAuth scopes in API Gateway side, then you must use access token. And no scope is configured then you can use ID token for authorization.
That said, you can try from Postman application for testing purpose.

Does PayPal still support activity report and balance via HTTP REST API?

thanks for reading - my questions are simple:
What am I doing wrong?
What am I missing?
Do I need to additional access to make use of the report engine?
I cannot seem to obtain balance or transaction data from my pp account using a simple python client despite what appears to be correct use of documented APIs.
I have:
a business account
dev portal access
valid creds for a Sandbox and Live API use
My py client wraps a few API calls and successfully completes the following:
obtain API token using dev portal creds
use API token to make valid HTTP requests to the balances and transactions API resources
API responses indicate 200 OK
However, except for the OAuth token request, all of the responses all say Empty XML data
Pseudo-sample code
# -- pp_auth_header is a global, contains Auth Bearer token
def get_balances():
print("get_balances...")
headers = pp_auth_header
endpoint = "/v1/reporting/balances"
query = "?currency_code=USD&as_of_time=2021-02-22T00:00:00-0700"
r = requests.get(pp_report_eng_url + endpoint + query, headers=pp_auth_header)
print("get_balances - status: {}".format(r.status_code))
if r.status_code == 200:
print("get_balances - r.text: {}".format(r.text))
# -- output of the above is
get_balances...
get_balances - url: https://api-m.sandbox.paypal.com/v1/reporting/balances?currency_code=USD&as_of_time=2021-02-22T00:00:00-0700
get_balances - status: 200
get_balances - r.text: Empty XML data
Generate an acess_token and then test from the command line with curl, as documented:
curl -v -X GET
https://api-m.sandbox.paypal.com/v1/reporting/balances?currency_code=USD&as_of_time=2016-10-15T06:07:00-0700
\
-H "Content-Type: application/json" \
-H "Authorization: Bearer Access-Token"
Ensure you pass the headers described there, including "Content-Type: application/json".
PayPal REST APIs do not return XML.
If this doesn't work, post the output of that curl -v command as well as the scopes returned by the oauth2 token request. Update your question with those details.

Python Requests OAuth2 header with access token

I am trying to use Python requests to use the API of Adform. How do I exactly include the access token (which I could successfully retrieve already) in my get request header?
I understand the API is based on OAuth2, and I am trying to use Client Credentials authorization. Here is the API docs: http://api.adform.com/help/guides/authorization-guide#consumingapis
I really can't tell the exact format of my header from this small amount of information.
I've tried:
requests.get(url, headers={'Authorization': 'MY_TOKEN_HERE'}
requests.get(url, headers={'Authorization': 'Bearer MY_TOKEN_HERE'}
requests.get(url, headers={'Authorization': 'access_token MY_TOKEN_HERE'}
None works unfortunately, all return <401> unauthorized. My access token is valid for sure.
requests.get(url, headers={'Authorization': 'Bearer MY_TOKEN_HERE'} should work, as long as MY_TOKEN_HERE is valid.
You may use requests_oauth2client to format the header properly with an AuthHandler:
from requests_oauth2client import BearerAuth
requests.get(url, auth=BearerAuth("MY_TOKEN_HERE"))
And you may even use it to get the access token easily, and have a requests Session that will automatically get the token as required and cache it as long as it is valid from next API calls:
from requests_oauth2client import OAuth2Client, OAuth2ClientCredentialsAuth
import requests
# define your OAuth2 client, with a Token Endpoint URL, a Client ID and a secret.
client = OAuth2Client("https://url.to.the.token.endpoint", auth=("CLIENT_ID", "CLIENT_SECRET"))
# use a session to benefit from token caching
session = requests.Session()
session.auth = OAuth2ClientCredentialsAuth(client, scope="YOUR_SCOPE"))
resp = session.get(url) # an access token will be obtained as required at this point before the API call is done
this one
curl --location --request GET
'https://api.adform.com/v1/seller/publishers' \
--header 'Authorization: Bearer MY_TOKEN_HERE'

Get Twitch channel ID from Python

It just says {"error":"Unauthorized","status":401,"message":"error getting authorization token"}, don't know why as I can write on chat with my token.
Here's the code:
url = "https://api.twitch.tv/kraken/channel"
channel_id = urllib.request.Request(url)
channel_id.add_header("Client-ID", CLIENT_ID)
#MY_OAUTH defined as MY_OAUTH = "oauth:123blablabla"
channel_id.add_header("Authorization: OAuth", MY_OAUTH")
response = urllib.request.urlopen(channel_id)
tmpJSON = json.loads(response.read())
EDIT: Here's the Pastebin of get_channel_id function: https://pastebin.com/Jm0EuWk9
It seems that your Authorization header is ill-formed. Supposing that MY_OAUTH as your access token, I believe you meant to write :
channel_id.add_header("Authorization", "OAuth " + MY_OAUTH)
Indeed, the Twitch-API authentication documentation recommends performing the following request when passing the access token in the HTTP header:
curl -H "Authorization: OAuth [access token]" https://api.twitch.tv/kraken/
As you can see, the header needs to be set as Authorization: OAuth [access token], instead of Authorization: OAuth: [access token].

Paypal Rest API - Creating payment using paypal account payment resource

Using python and django, I'm trying to create a payment on paypal using REST API account payment resource. Everything works when I use curl. In the Django view I get the token alright but when I try to make a payment using it, I get "HTTP Error 401: Unauthorized" error.
Here is my curl that works:
curl -v https://api.sandbox.paypal.com/v1/payments/payment -H 'Content-Type:application/json' -H 'Authorization:Bearer ***my_token***' -d '{ "intent":"sale", "redirect_urls":{ "return_url":"http://www.myurl.com", "cancel_url":"http://www.myurl.com"}, "payer":{ "payment_method":"paypal" },"transactions":[{"amount":{ "total":"0.10", "currency":"USD"},"description":"This is the Test payment transaction description."}]}'
Here is my Django view that has a problem when :
import urllib2, base64
token = "***my_token***"
values = {
"intent":"sale",
"redirect_urls":{
"return_url":"http://www.myurl.com",
"cancel_url":"http://www.myurl.com"
},
"payer":{
"payment_method":"paypal"
},
"transactions":[
{
"amount":{
"total":"0.10",
"currency":"USD"
},
"description":"This is the Test payment transaction description."
}
]}
data = urllib.urlencode(values)
request1 = urllib2.Request("https://api.sandbox.paypal.com/v1/payments/payment")
base64string = base64.encodestring('%s' % token).replace('\n', '')
request1.add_header("Content-Type", "application/json")
request1.add_header("Authorization", "Bearer %s" % base64string)
result1 = urllib2.urlopen(request1 , data)
response = result1.read()
In other words I'm trying to make the curl work in my view.
Thanks.
Not sure if you're running into the same thing I was, but I was trying to create payments for a third party paypal account to which I had not properly requested permission. Turns out I needed to use the Permissions API to request proper permissions.
See this link: https://developer.paypal.com/webapps/developer/docs/classic/permissions-service/integration-guide/PermissionsAbout/
First make a request to https://api.sandbox.paypal.com/v1/oauth2/token with basic auth to get Bearer token and then make the REST call(https://api.sandbox.paypal.com/v1/payments/payment) with the Bearer token.
https://developer.paypal.com/webapps/developer/docs/integration/direct/make-your-first-call/
Use PayPal SDK paypalrestsdk to simplify your Python code.
https://github.com/paypal/rest-api-sdk-python - README
https://github.com/paypal/rest-api-sdk-python/tree/master/samples - Samples

Categories

Resources