Python twitch api unable to get authorization on request - python

I'm trying to get data about a stream via the twitch api, the first request for the oauth2 token works perfectly, but then as soon as I make the first request I get this error 401 Client Error: Unauthorized for url: https://api.twitch.tv/helix/users?login=im_marcotv&. What I understand is that there is an error in my token submission, but I don't understand what I did wrong, this is the complete code:
import requests
import os
import json
from dotenv import load_dotenv
load_dotenv()
CLIENTID = os.getenv("CLIENTID")
CLIENTSID = os.getenv("CLIENTSID")
sCLIENTID = str(CLIENTID)
sCLIENTSID = str(CLIENTSID)
if __name__ == "__main__":
print("print1")
request_token_url = f'https://id.twitch.tv/oauth2/token?
client_id=&client_secret=&grant_type=client_credentials'
response = requests.post(request_token_url)
response.raise_for_status()
print(response.json())
token = json.loads(response.text)["access_token"]
print(f"Token: {token}")
header = {"Client-ID": "", f"Authorization": "Bearer {token}"}
response = requests.get("https://api.twitch.tv/helix/users?login=im_marcotv&", headers=header)
response.raise_for_status() #line that raise the error
print(response.json())
data = json.loads(response.text)["data"]
if data:
streamer = data[0]
user_name = streamer["user_name"]
game_name = streamer["game_name"]
viewer_count = streamer["viewer_count"]
output = f"{user_name} is online on {game_name} con {viewer_count} visualizzazioni"
print(output)
else:
#print(f"{name} is offline")
pass
The line getting the token was also giving the same error, but I fixed it by stopping using variables to hold the client id and secret id. In all the places where there should be the ids I removed them, but in the actual code they are present and correct

Related

Request API with Bearer token

I am trying to use the Malwarebytes API to get data. However, I am not getting the results for request. I get the "Unauthorized" message. My understanding of the documentation is to get the "access token" using my client ID and client secret. I was able to get the access token. However, I am not sure how to run the access token I received to the headers so I can get data. help is appreciated.
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
import requests
import json
CLIENT_ID = "Client id "
CLIENT_SECRET = "client secret"
grant_type = 'client_credentials'
body_params = {'grant_type' : grant_type}
url='https://api.malwarebytes.com/oneview/oauth2/token'
response = requests.post(url, data=body_params, auth = (CLIENT_ID, CLIENT_SECRET))
#Gets only access token
response_token = response.json()
response_token2 = json.dumps(response_token, indent=2)
token_response = response_token.get("access_token",[0])
##BEARER AUTHORIZATION
headers = {
'Authorization':'Bearer token_response',
'Content-Type':'application/x-www-form-urlencoded'
}
companies = requests.get('https://api.malwarebytes.com/oneview/v1/sites', headers=headers)
print(companies.text)
print(companies.status_code)
Issue with getting data after getting access token

Sign in Firebase backend using python

I am trying to use Python to sign into Firebase backend, get a token then pass it to an endpoint to fetch transaction information. Below is the code example.
import json
import requests
def sign_in_with_email_and_password(email, password, return_secure_token=True):
payload = json.dumps({"email":email, "password":password, "return_secure_token":return_secure_token})
FIREBASE_WEB_API_KEY = '__API_KEY__'
rest_api_url = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword"
r = requests.post(rest_api_url,
params={"key": FIREBASE_WEB_API_KEY},
data=payload)
return r.json()
user = sign_in_with_email_and_password('test#test.com.', 'password1234')
transaction = requests.get('https://app.appspot.com/invoices/getTransaction?transactionId=543453',
headers={'Authorization': user['idToken']})
print(transaction.json())
I am not sure where it goes wrong; I get an error as below.
{'code': 'auth/argument-error', 'message': 'First argument to verifyIdToken() must be a Firebase ID token string.'}
Can you please help verify what I have done wrong?

Verification of Okta token in Python

I would like to verify an Okta token (RS256) in python. I have tried to find the solution online but have not managed to get it to work:
I have tried this so far:
from py_jwt_validator import PyJwtValidator, PyJwtException
jwt = OKTA_TOKEN
try:
PyJwtValidator(jwt)
except PyJwtException as e:
print(f"Exception caught. Error: {e}")
throwing the error:
Okta-Specific: Access Tokens can not be validated locally without a Custom Authorization Server.
I have also tried to use the okta endpoint /introspect, but I keep on getting Response 405. I try to do get request to introspect/client_id=CLIENT_ID&token_type_hint=access_token&token=TOKEN
I also tried several other packages including okta_jwt (complains about ErrorKey : "jwks_uri")...
I found an answer to my own question. I can use the /introspect endpoint of okta:
headers = {"Content-type": "application/x-www-form-urlencoded"}
http = urllib3.PoolManager()
url = ".../oauth2/v1/introspect/"
token = TOKEN
client_id = YOUR_CLIENT_ID
data = "client_id={}&token_type_hint=access_token&token={}".format(client_id, token)
response = http.request('POST', url, body=data, headers=headers)
decoded_response = response.data.decode('utf-8')
json_response = json.loads(decoded_response)
json_response["active"] will then be true if the token has been validated and false if its not the case.

oauth2 POST - twitter

i created a script that will get the users friend list (GET request) and i was successful. Now i am attempting to make a script that will follow a particular user (POST request) and i've been unsuccessful.
here is my oauth function (where the problem lies):
def augment_POST(url,**kwargs) :
secrets = hidden.oauth()
consumer = oauth2.Consumer(secrets['consumer_key'], secrets['consumer_secret'])
token = oauth2.Token(secrets['token_key'],secrets['token_secret'])
oauth_request = oauth2.Request.from_consumer_and_token(consumer, token= token, http_method='POST', http_url=url, parameters=kwargs)
oauth_request.to_postdata() # this returns post data, where should i put it?
oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token)
return oauth_request.to_url()
my augment_GET function is the exact same thing except http_mehtod='GET'
for clarity:
def follow_user(id):
seedurl="https://api.twitter.com/1.1/friendships/create.json"
print 'Attempting to follow: %d' % (id,)
url = augment_POST(seedurl,user_id=id)
connection = urllib.urlopen(url)
data = connection.read()
headers = connection.info().dict
any help will be greatly appreciated.
First it seems you need to import urllib2 to make a POST request.
You have to send the POST data that you get from the to_postdata method
using the data argument of urlopen:
def augment_POST(url, **kwargs) :
secrets = hidden.oauth()
consumer = oauth2.Consumer(secrets['consumer_key'],
secrets['consumer_secret'])
token = oauth2.Token(secrets['token_key'],
secrets['token_secret'])
oauth_request = oauth2.Request.from_consumer_and_token(
consumer,
token= token,
http_method='POST',
http_url=url,
parameters=kwargs
)
oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(),
consumer, token)
# this is the data that must be sent with you POST request
return oauth_request.to_postdata()
def follow_user(id):
url = "https://api.twitter.com/1.1/friendships/create.json"
print 'Attempting to follow: %d' % id
postdata = augment(url, method='GET', user_id=id)
# Send the POST request with the data argument
# The url is the same as the data is sent in the body of the request
connection = urllib2.urlopen(url, data=postdata)
data = connection.read()
headers = connection.info().dict
I would recommend to use the requests_oauthlib module which makes all this really easy:
from requests_oauthlib import OAuth1Session
tokens = hidden.oauth()
client = OAuth1Session(tokens['consumer_key'],
tokens['consumer_secret'],
tokens['token_key'],
tokens['token_secret'])
def follow_user(id):
url = "https://api.twitter.com/1.1/friendships/create.json"
print 'Attempting to follow: %d' % id
# for GET requests use client.get and the `params` argument
# instead of the `data` argument
response = client.post(url, data={'user_id': id})
data = response.text
# or even `data = response.json()` to decode the data
headers = response.headers

Python's urllib2/oauth2 request to UbuntuOne file api returns a 401 unauthorized error

I'm trying to issue a basic UbuntuOne API call.
As explained on https://one.ubuntu.com/developer/account_admin/auth/otherplatforms, I'm getting the OAUTH token and then passing it to the UbuntuOne service.
I get the token and consumer info alright
I'm then trying to issue a /api/file_storage/v1 API call (see: https://one.ubuntu.com/developer/files/store_files/cloud.) The request is signed using the OAUTH token.
The code snippet below is the exact code I'm executing (minus the email.password/description fields.) The token and consumer data is returned properly. I'm getting a '401 UNAUTHORIZED' from the server when issuing the /api/file_storage/v1 request... any idea why?
import base64
import json
import urllib
import urllib2
import oauth2
email = 'bla'
password = 'foo'
description = 'bar'
class Unauthorized(Exception):
"""The provided email address and password were incorrect."""
def acquire_token(email_address, password, description):
"""Aquire an OAuth access token for the given user."""
# Issue a new access token for the user.
request = urllib2.Request(
'https://login.ubuntu.com/api/1.0/authentications?' +
urllib.urlencode({'ws.op': 'authenticate', 'token_name': description}))
request.add_header('Accept', 'application/json')
request.add_header('Authorization', 'Basic %s' % base64.b64encode('%s:%s' % (email_address, password)))
try:
response = urllib2.urlopen(request)
except urllib2.HTTPError, exc:
if exc.code == 401: # Unauthorized
raise Unauthorized("Bad email address or password")
else:
raise
data = json.load(response)
consumer = oauth2.Consumer(data['consumer_key'], data['consumer_secret'])
token = oauth2.Token(data['token'], data['token_secret'])
# Tell Ubuntu One about the new token.
get_tokens_url = ('https://one.ubuntu.com/oauth/sso-finished-so-get-tokens/')
oauth_request = oauth2.Request.from_consumer_and_token(consumer, token, 'GET', get_tokens_url)
oauth_request.sign_request(oauth2.SignatureMethod_PLAINTEXT(), consumer, token)
request = urllib2.Request(get_tokens_url)
for header, value in oauth_request.to_header().items():
request.add_header(header, value)
response = urllib2.urlopen(request)
return consumer, token
if __name__ == '__main__':
consumer, token = acquire_token(email, password, description)
print 'Consumer:', consumer
print 'Token:', token
url = 'https://one.ubuntu.com/api/file_storage/v1'
oauth_request = oauth2.Request.from_consumer_and_token(consumer, token, 'GET', url)
oauth_request.sign_request(oauth2.SignatureMethod_PLAINTEXT(), consumer, token)
request = urllib2.Request(url)
request.add_header('Accept', 'application/json')
for header, value in oauth_request.to_header().items():
request.add_header(header, value)
response = urllib2.urlopen(request)
The issue was with the 'description' field. It must be in the following format:
Ubuntu One # $hostname [$application]
Else, the UbuntuOne service returns a "ok 0/1" and does not register the token.

Categories

Resources