Request API with Bearer token - python

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

Related

Python - OAUTH2 How to get access token using PCKE?

I am trying to get this access token with Python. With Postman I can get an access token. After configurations in the screenshots, I click the Get Access Token button, and A pop-up throws for username and password. Then I fill them. After that, I can get an access token from Postman.
To get an access token with Python, I wrote the code below. In the first get request, I get the cookies and Redirect URL(to post user credentials). Then, I post user credentials and cookies to Redirected URL. After that, the response header["location"] must include a code parameter to get the token. But, the header parameter does not have a code parameter. It has an Authorization URL with query parameters. How can get this code parameter? Finally, I will post a request(to token URL) with this code to get an access token on the response body.
import base64
import hashlib
import json
import os
import re
import urllib.parse
import requests
from bs4 import BeautifulSoup
from rich import print
username = 'username '
password = 'password '
client_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxx'
client_secret = 'yyyyyyyyyyyyyyyyyyyyyyyyyy'
prod_url = 'https://url:port'
callback_url = prod_url + '/main/ifsapplications/projection/oauth2/callback'
authorization_url = prod_url + '/openid-connect-provider/idp/authorization'
token_url = prod_url + '/openid-connect-provider/idp/token'
code_challenge_method = "S256" #SHA-256
scope = 'openid'
response_type ='code'
#Add auth data to request headers
#Grant type = authorization code with pkce
#send client credentials in body
code_verifier = base64.urlsafe_b64encode(os.urandom(40)).decode('utf-8')
code_verifier = re.sub('[^a-zA-Z0-9]+', '', code_verifier)
code_challenge = hashlib.sha256(code_verifier.encode('utf-8')).digest()
code_challenge = base64.urlsafe_b64encode(code_challenge).decode('utf-8')
code_challenge = code_challenge.replace('=', '')
resp = requests. Get(
url=authorization_url,
params={
"response_type": response_type,
"client_id": client_id,
"scope": scope,
"redirect_uri": callback_url,
"code_challenge": code_challenge,
"code_challenge_method": code_challenge_method,
},
allow_redirects=False
)
cookie = resp.headers['Set-Cookie']
cookie = '; '.join(c.split(';')[0] for c in cookie. Split(', '))
soup = BeautifulSoup(resp.text, 'html.parser')
form_action = soup. Find('a').text
resp = requests. Post(
url=form_action,
data={
"username": username,
"password": password
},
headers={"Cookie": cookie,
"Referer": form_action},
allow_redirects=False
)
redirect = resp.headers['Location']
print(resp.text)
print(resp.headers)
OUTPUT:

How to add http headers along with data to send a POST request to an API endpoint using Oauth2Session (requests_oauthlib)?

I have a python code like this to interact with an API
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
import json
from pprint import pprint
key = "[SOME_KEY]" # FROM API PROVIDER
secret = "[SOME_SECRET]" # FROM API PROVIDER
api_client = BackendApplicationClient(client_id=key)
oauth = OAuth2Session(client=api_client)
url = "[SOME_URL_FOR_AN_API_ENDPOINT]"
# GETTING TOKEN AFTER PROVIDING KEY AND SECRET
token = oauth.fetch_token(token_url="[SOME_OAUTH_TOKEN_URL]", client_id=key, client_secret=secret)
# GENERATING AN OAuth2Session OBJECT; WITH THE TOKEN:
client = OAuth2Session(key, token=token)
body = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
response = client.post(url, data=json.dumps(body))
pprint(response.json())
When I run this py file, I get this response from the API, that I have to include the content type in the header. How do I include the header with Oauth2Session?
{'detailedMessage': 'Your request was missing the Content-Type header. Please '
'add this HTTP header and try your request again.',
'errorId': '0a8868ec-d9c0-42cb-9570-59059e5b39a9',
'simpleMessage': 'Your field could not be created at this time.',
'statusCode': 400,
'statusName': 'Bad Request'}
Have you tried to you send a header paramter with this requests?
headers = {"Content-Type": "application/json"}
response = client.post(url, data=json.dumps(body), headers=headers)
This is how I was able to configure the POST request for exchanging the code for a token.
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import WebApplicationClient, BackendApplicationClient
from requests.auth import HTTPBasicAuth
client_id = CLIENT_ID
client_secret = CLIENT_SECRET
authorization_base_url = AUTHORIZE_URI
token_url = TOKEN_URI
redirect_uri = REDIRECT_URI
auth = HTTPBasicAuth(client_id, client_secret)
scope = SCOPE
header = {
'User-Agent': 'myapplication/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
}
# Create the Authorization URI
# Not included here but store the state in a safe place for later
the_first_session = OAuth2Session(client_id=client_id, redirect_uri=redirect_uri, scope=scope)
authorization_url, state = the_first_session.authorization_url(authorization_base_url)
# Browse to the Authorization URI
# Login and Auth with the OAuth provider
# Now to respond to the callback
the_second_session = OAuth2Session(client_id, state=state)
body = 'grant_type=authorization_code&code=%s&redirect_uri=%s&scope=%s' % (request.GET.get('code'), redirect_uri, scope)
token = the_second_session.fetch_token(token_url, code=request.GET.get('code'), auth=auth, header=header, body=body)

How to access spotify's web api with client id and secret?

I'm trying to write a script that creates a playlist on my spotify account in python, from scratch and not using a module like spotipy.
My question is how do I authenticate with my client id and client secret key using the requests module or grab an access token using those credentials?
Try this full Client Credentials Authorization flow.
First step – get an authorization token with your credentials:
CLIENT_ID = " < your client id here... > "
CLIENT_SECRET = " < your client secret here... > "
grant_type = 'client_credentials'
body_params = {'grant_type' : grant_type}
url='https://accounts.spotify.com/api/token'
response = requests.post(url, data=body_params, auth = (CLIENT_ID, CLIENT_SECRET))
token_raw = json.loads(response.text)
token = token_raw["access_token"]
Second step – make a request to any of the playlists endpoint. Make sure to set a valid value for <spotify_user>.
headers = {"Authorization": "Bearer {}".format(token)}
r = requests.get(url="https://api.spotify.com/v1/users/<spotify_user>/playlists", headers=headers)
print(r.text)
As it is referenced here, you have to give the Bearer token to the Authorization header, and using requests it is done by declaring the "headers" optional:
r = requests.post(url="https://api.spotify.com/v1/users/{your-user}/playlists",
headers={"Authorization": <token>, ...})
The details of how can you get the Bearer token of your users can be found here

Rest API with oauth2 work just in browser, error in python

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

"Error parsing JSON" when using Spotify API

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)

Categories

Resources