I am using urllib and urllib2 to get request token from twitter as recommended here https://dev.twitter.com/docs/auth/implementing-sign-twitter, code is below. Can anyone see, what am I doing wrong? I get 'urllib2.HTTPError: HTTP Error 401: Unauthorized'
#! env python
import sys
import os
import urllib
import urllib2
import uuid
import time
import base64
import string
# 1. Obtain a request token
# 2. Redirect the user
# 3. Convert the request token to an access token
consumer_key= "xxxxxxx"
consumer_secret= "xxxxxxxxxxxxxxx"
# Request token URL: https://api.twitter.com/oauth/request_token
# Authorize URL: https://api.twitter.com/oauth/authorize
# Access token URL: https://api.twitter.com/oauth/access_token
nonce = base64.b32encode(str(uuid.uuid4().hex))
# example: MYZTMMRYMEYDQN3FMFSDIYJXGNRDCMBWG42TAMJUGVTGGMZRMFSA====
nonce = nonce.rstrip('=')
print 'Nonce', nonce
data = { 'oauth_callback' : 'http://www.gooogle.com',
'oauth_consumer_key' : 'bwKT66akiJSin30L1mGnQ',
'oauth_nonce' : nonce,
'oauth_timestamp' : int(time.time()),
'oauth_version' : "1.1"
}
url_values = urllib.urlencode(data)
url = 'https://api.twitter.com/oauth/request_token'
full= url + '?' + url_values
data = urllib2.urlopen(full)
Which all query parameters are mandatory here?
Related
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
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:
I try to acess data from an Exchange Platform with API.
I have my API_Key and my SECRET_KEY, and I have the documentation of that Platform here:
https://apidocs.exir.io/
I generate the "signature-key" just as described in the documentation under "Authentication" chapter and then try to test it with a sample GET request with only one parameter.
Now if I run the Code I get "message": "Access Denied: Invalid API Signature"
Can you please help me to find the wrong thing in this code?
I think I do something wrong with params because if I use other GET orders without parameters it works!
Thank you in advance!
import time
import json
import hmac
import hashlib
import requests
API_KEY = '*****'
SECRET_KEY = '*****'
BASE_URL = 'https://api.exir.io'
timestamp = str(int(time.time()+10))
headers = {
'api-key': API_KEY,
'api-expires': timestamp} # see documentation under "Authentication"
PATH = '/v1/user/orders' # This ist just a simple example, which uses "params". See Exir documentation under "Get All Orders"
params = {"symbol":"btc-irt"}
string = 'GET'+timestamp+str(params) # see Exir API doumentation under "Authentication"
headers['api-signature'] = hmac.new(SECRET_KEY.encode('utf-8'), string.encode('utf-8'), hashlib.sha256).hexdigest()
url = 'https://api.exir.io/v1/user/orders?symbol=btc-irt'
r = requests.get(url, headers=headers)
data = r.json()
print(json.dumps(data, indent=2))
A lot of what you are doing is unnecessary, actually. The requests library handles most of what you are trying to do.
import requests
API_KEY = '*****'
SECRET_KEY = '*****'
BASE_URL = 'https://api.exir.io'
timestamp = str(int(time.time()+10))
headers = {
'api-key': API_KEY,
'api-expires': timestamp
}
url = 'https://api.exir.io/v1/user/orders?symbol=btc-irt'
r = requests.get(url, headers=headers)
The library will do the encoding for you.
You mixed the post and get request parameters. For the get request, you only need to include the params in the URL to sign. In your case it will be:
PATH = '/v1/user/orders?symbol=btc-irt'
string = 'GET/' + PATH + timestamp
Hi I´m new trying to get data from Apis:
Im trying to send an email from a Qt app getting the email and password from a text_edit my problem is when im trying to get the api auth from microsoft(Azure)
from urllib.parse import quote, urlencode
import base64
import json
import time
# Client ID and secret
client_id = 'UUUUUUUUUUUUUUUUUUUUUUUU'
client_secret = ' PPPPPPPPPPPPPPPPP'
# Constant strings for OAuth2 flow
# The OAuth authority
authority = 'https://login.microsoftonline.com'
# The authorize URL that initiates the OAuth2 client credential flow for admin consent
authorize_url = '{0}{1}'.format(authority, '/common/oauth2/v2.0/authorize?{0}')
# The token issuing endpoint
token_url = '{0}{1}'.format(authority, '/common/oauth2/v2.0/token')
# The scopes required by the app
scopes = [ 'Mail.Read',
'Mail.Send' ]
def get_signin_url(redirect_uri):
# Build the query parameters for the signin url
params = { 'client_id': client_id,
'redirect_uri': redirect_uri,
'response_type': 'code',
'scope': ' '.join(str(i) for i in scopes)
}
signin_url = authorize_url.format(urlencode(params))
return signin_url
This code is to generate the url to login that is called by:
def Message_Send():
Sign = QS.get_signin_url('Directorio://auth')
data={
'loginfmt':'XXXXXXXXX',
'passwd':'YYYYYYYYY'
}
requ = requests.Session()
geto=requ.post(Sign,)
But when i try to get a json from geto app crashes and if I use geto.text show me a kind of HTML page without body
json.decoder.JSONDecodeError: Expecting value: line 3 column 1 (char 4)
This is the error when use json
I get status code 200
the app UI is made by pyqt
Im struggling with this Dokumentation here:
Send your credential base64 encoded to the authentication server.
Get a response including an UUID for authentication.
Use the UUID to authenticate REST requests.
It shows this request as an example:
**Header**
“`json
{
‘Content-Type’: ‘application/x-www-form-urlencoded’,
‘authorization’: ‘Basic <base64 encoded username:password>’
}
“`
**Body**
“`json
{
‘grant_type’: ‘client_credentials’
}
“`
How do I turn with into a requests.post() ?
you have to build dictionaries and post them with requests :
import requests
import base64
import json
username = "user"
password = "password"
url = 'https://myurl.com'
headers = {}
headers['Content-Type'] = 'application/x-www-form-urlencoded'
headers['authorization'] = 'Basic ' + base64.b64encode(bytes(username + ':' + password, 'utf-8')).decode('utf-8')
body = {}
body['grant_type'] = 'client_credentials'
r = requests.post(url, data=json.dumps(body), headers=json.dumps(headers))