Get Twitch channel ID from Python - 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].

Related

How get bearer token with requests from python

I'm trying to replicate a login to a page with python and the requests module but I need a token bearer.
This site doesn't require a login password connection but just an event code (wooclap.com)
I cannot find when the token is recovered by looking at header and json responses.
If you can help me
Thanks
once you put in a event code check the network tab on you're chrome console there should be a request wich returns the token. either in the reponse header or the json,
I'd recommend finding it using DevTools in your browser (F12).
In network you can see the login request mainly under headers and response. I've used this to implemented it below in python for you.
import requests
# Set the URL of the login page
url = "https://app.wooclap.com/api/auth/local/login"
# Set the login credentials
data = {"username": "< !!enter username here!! >", "password": "< !!enter password here!! >"}
# Send the login request and store the response
response = requests.post(url, data=data)
# Get the JSON response body
json_response = response.json()
# Get the AWT token from the JSON response
awt_token = json_response.get("token")
# Set the URL of the resource you want to access
url = "https://app.wooclap.com/public/events"
# Set the authorization header of your request, using the Bearer scheme
headers = {"Authorization": f"Bearer {awt_token}"}
# Send the request and store the response
response = requests.get(url, headers=headers)
print(response.text)
To send a GET request with a Bearer Token authorization header using Python, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header

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.

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

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)…'},

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'

How to replace token(bearer) with username, password in Cherwell REST API request

I am trying to create RFC in cherwell using REST API in Python. I tried first in Swegger UI. I got it working there. I am able to create RFC successfully. Then by following that Curl Request, in python, using request module, I tried and got 401. I found it why i am getting 401. It's because of in Authorization i am using Bearer which is a temporary token. It will live only for 10 minutes. If i do request after 10 minutes i got a 401. Bearer is a compulsory field. I can't make a request without it. I tried to pass username and password instead of Bearer, it didn't work. below is my request,
with open('C:\Cherwell\payload.json') as file:
Data = json.load(file)
payload = Data
header = {"Authorization":"Bearer XXXXXXXX"}
r = requests.post("https:/URL/CherwellAPI/api/V1/savebusinessobject?
api_key=XXXX-XXXX-XXXX-XXXX", auth=('user','pass'), headers = header,
data=json.dumps(payload))
print r
It will be great, if anyone can help who have done this before! Please Advice
Appreciate any help!
Found this solution that I used to address a similar problem. It's a function that requests a token from /CherwellAPI/token and returns a properly formatted Bearer token. You need to pass this Bearer token along in API requests as a Authorization parameter in the API header. Should look like token=bearer_token.
import json
import requests
configFile = 'config.json'
with open(configFile) as cf:
config_data = json.load(cf)
def getCherwellToken():
params = {'apikey' : config_data['cherwell']['client_id']}
data = {'grant_type' : 'password',
'client_id' : config_data['cherwell']['client_id'],
'username' : config_data['cherwell']['username'],
'password' : config_data['cherwell']['password']}
url = 'https://.cherwellondemand.com/CherwellAPI/token'
session = requests.post(url=url, data=data)
if session:
token = json.loads(session.text)
else:
token = None
return 'Bearer ' + token['access_token']
using another call Get Token You can get access token and using that you can request to create a new ticket. This worked for me.

Categories

Resources