call OAUTH2 api in python script - python-3.x

i have found this interesting article here https://developer.byu.edu/docs/consume-api/use-api/oauth-20/oauth-20-python-sample-code
in this article there is an example how to call an oauth2 api using authorization_code flow. the problem with this approach is that you need to open a new browser, get the code and paste in the script. i would open and get the code directly from python script. is it possible?
print "go to the following url on the browser and enter the code from the
returned url: "
print "--- " + authorization_redirect_url + " ---"
access_token = raw_input('access_token: ')

I have been battling with this same problem today and found that the following worked for me. You'll need:
An API ID
A secret key
the access token url
I then used requests_oauthlib: https://github.com/requests/requests-oauthlib
from requests_oauthlib import OAuth2Session
# Both id and secret should be provided by whoever owns the api
myid = 'ID_Supplied'
my_secret = 'Secret_pass'
access_token_url = "https://example.com/connect/token" # suffix is also an example
client = BackendApplicationClient(client_id=myid)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=access_token_url, client_id=myid,
client_secret=my_secret)
print(token)

Related

How to handle ezproxy authorization to download data through API?

I have a token to have an access to download large files from the comtrade. The original webpage is http://comtrade.un.org/ however I have a premium access through my university library subscription. So,if I want to use the premium features the website automatically redirects me to this page and after pressing login button the URL is https://ezproxy.nu.edu.kz:5588/data/dev/portal/. I am trying to send request and download files with API(using requests). I am getting response from http://comtrade.un.org/ but in order to download I need to use https://ezproxy.nu.edu.kz:5588/data/dev/portal/. and when I tried to download urllib.error.HTTPError: HTTP Error 401: Unauthorized this error message appeared. How can I handle this problem?
px = 'px=HS&' #classification
freq = 'freq=A&' #annual
type = 'type=C&' #commodity
auth = 'https://comtrade.un.org/api/getUserInfo?token=ZF5TSW8giRQMFHuPmS5JwQLZ5FB%2BNO0NCcjxFQUJADrLzCRDCkG5F0ZPnZTYQWO3MPgj96gZNF7Z9iN8BwscUMYBbXuDVYVDvsTAVNzAJ6FNC2dnN7gtB1rt9qJShAO467zBegHTLwvmlRIBSpjjwg%3D%3D'
with open('reporterAreas.json') as json_file:
data = json.load(json_file)
ls = data['results']
list_year = [*range(2011, 2021,1)]
for years in list_year:
print(years)
ps = 'ps='+ str(years) + '&'
for item in ls:
r = item['id'] #report_country_id
report_country_txt = item['text']
if r == 'all':
req_url = 'r=' + r + '&' + px + ps + type + freq + token
request = url + req_url
response = requests.get(request)
if response.status_code == 200:
print("Response is OK!")
data = response.json()[0]
download_url = dwld_url + data['downloadUri']
print(download_url)
filename = str(years) + '_' + report_country_txt + '.zip'
urllib.request.urlretrieve(url, filename)
I'm not sure if Ezproxy provides an API or SDK way to authenticate a request but i don't think.
What you could do is to provide the Ezproxy session to your request and with that, you request will not be treated as unauthorized because you're passing a valid session and therefore your request will be treated as a valid one.
Notice that you can retrieve your Ezproxy session id from your cookies.
And finally, you have to make your request against the starting point url
Otherwise, you can use selenium to fill automatically the login form and retrieve the Ezproxy session id to pass it to the requests.
I hope this could help you !

Unable to authenticate Looker API in Databricks using Python

I want to access some charts -which I have saved in Looker- within Databricks. Part of this process is the authentication. I have one Looker auth-script which works but only pulls the tabular results into Databricks which corresponds to a Looker-View. Instead, I want ONLY the charts to be accessed in Databricks which will correspond to a Looker-look or Looker-space. However, when I follow the tutorial on https://discourse.looker.com/t/generating-a-powerpoint-presentation-from-all-looks-in-a-space/8191, I am not able to authenticate with their script. Hopefully, someone can help.
**Working auth-script for Looker-Views**
import looker_tools as tools
api=tools.LookerApi(
api_endpoint="abcd",
client_id=dbutils.secrets.get(scope="looker-api", key="looker_client_id"),
client_secret=dbutils.secrets.get(scope="looker-api",key="looker_client_secret")
)
token = api.login()
**Desired auth-script for Looker-Space/Looks as per tutorial link**
looker_instance = 'your-company.looker.com'
target_space = # 'Period over Period' Space on the Looker instance
client_id = 'xxxxxxxx'
client_secret = 'xxxxxxxx'
# instantiate Auth API
unauthenticated_client = looker_client.ApiClient(configuration=None)
unauthenticated_client.configuration.host = f'https://{looker_instance}:19999/api/3.0/'
unauthenticated_authApi = looker_client.ApiAuthApi(unauthenticated_client)
# authenticate client
token = unauthenticated_authApi.login(client_id=client_id, client_secret=client_secret)
client = looker_client.ApiClient(header_name='Authorization', header_value='token ' + token.access_token)
client.configuration.host = f'https://{looker_instance}:19999/api/3.0/'
I tried translating the code from Current to DESIRED auth-script but the error states the looker_client is not defined!
looker_instance = 'abcd'
target_space = 123
client_id = dbutils.secrets.get(scope="looker-api", key="looker_client_id")
client_secret = dbutils.secrets.get(scope="looker-api",key="looker_client_secret")
# instantiate Auth API
unauthenticated_client = looker_client.ApiClient(configuration=None) --> This line fails!!
unauthenticated_client.configuration.host = f'https://{looker_instance}:19999/api/3.0/'
unauthenticated_authApi = looker_client.ApiAuthApi(unauthenticated_client)
# authenticate client
token = unauthenticated_authApi.login(client_id=client_id, client_secret=client_secret)
client = looker_client.ApiClient(header_name='Authorization', header_value='token ' + token.access_token)
client.configuration.host = f'https://{looker_instance}:19999/api/3.0/'
I hope someone can help on how to define looker_client properly. Thanks.
It looks like this one was resolved here: https://discourse.looker.com/t/generating-a-powerpoint-presentation-from-all-looks-in-a-space/8191/15?u=izzy for those following along at home. There's another issue, but the NameError: name ‘looker_client’ is not defined error was resolved by adding a necessary import:
import looker_client_30 as looker_client

Watson speech to text: Invalid credentials error (Code: 401)

I am trying to use the IBM Watson speech to text API/service in the following Python program.
import json
import os
import sys
from watson_developer_cloud import SpeechToTextV1
def transcribe_audio(audio_file_name) :
IBM_USERNAME = "yourusername"
IBM_PASSWORD = "yourpassword"
#what changes should be made here instead of username and password
stt = SpeechToTextV1(username=IBM_USERNAME, password=IBM_PASSWORD)
audio_file = open(audio_file_name, "rb")
json_file = os.path.abspath("america")+".json";
with open(json_file, 'w') as fp:
result = stt.recognize(audio_file,timestamps=True,content_type='audio/wav', inactivity_timeout =-1,word_confidence = True)
result.get_result()
json.dump(result, fp, indent=2)
script = "Script is : "
for rows in result['results']:
script += rows['alternatives'][0]['transcript']
print(script)
transcribe_audio("america.wav")
This code gave me an authentication error as mentioned in the title because IBM changed the authorization method from username + password to apikey
very recently.
Could anybody tell me what changes should be made in this?
And also how to generate the apikey on IBM Watson speech to text with username and password?
I am new to speech recognition, please let me know. Thanks in advance.
All the information you want is in the API documentation, including how to obtain the API Key - https://cloud.ibm.com/apidocs/speech-to-text?code=python

Google Slides API: no "client_secret.json"

I'm new to Google Slides API and am trying to build a slide deck for daily news headlines by replacing image and text placeholders (for your reference, see https://www.youtube.com/watch?v=8LSUbKZq4ZY and http://wescpy.blogspot.com/2016/11/using-google-slides-api-with-python.html).
But when I try to run my modified program, I get an error message that says no file or directory exists called "client_secret.json" (which is included in the API tutorial's code). The tutorial code is from 2 years ago so I'm not sure if there's been any updates in the Google Slides API, but I'd really appreciate help on navigating this issue. Below is my code (note: "scraped list" is a list of dictionaries, with each dictionary containing a value for keys "headline" and "imgURL".)
from __future__ import print_function
from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
from datetime import date
from scrapef2 import scrape
scrapedlist = scrape()
TMPLFILE = 'CrimsonTemplate' # use your own!
SCOPES = (
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/presentations',
)
store = file.Storage('storage.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
HTTP = creds.authorize(Http())
DRIVE = discovery.build('drive', 'v3', http=HTTP)
SLIDES = discovery.build('slides', 'v1', http=HTTP)
rsp = DRIVE.files().list(q="name='%s'" % TMPLFILE).execute().get('files')[0]
DATA = {'name': '[DN] '+ str(date.today())}
print('** Copying template %r as %r' % (rsp['name'], DATA['name']))
DECK_ID = DRIVE.files().copy(body=DATA, fileId=rsp['id']).execute().get('id') # TO DO: How to copy into a specific folder
for i in range(3):
print('** Get slide objects, search for image placeholder')
slide = SLIDES.presentations().get(presentationId=DECK_ID,
fields='slides').execute().get('slides')[i]
obj = None
for obj in slide['pageElements']:
if obj['shape']['shapeType'] == 'RECTANGLE':
break
print('** Replacing placeholder text and icon')
reqs = [
{'replaceAllText': {
'containsText': {'text': '{{Headline}}'},
'replaceText': scrapedlist[i]["headline"]
}},
{'createImage': {
'url': scrapedlist[i]["imgURL"],
'elementProperties': {
'pageObjectId': slide['objectId'],
'size': obj['size'],
'transform': obj['transform'],
}
}},
{'deleteObject': {'objectId': obj['objectId']}},
]
SLIDES.presentations().batchUpdate(body={'requests': reqs},
presentationId=DECK_ID).execute()
print('DONE')
Never used python google api but error indicates that you dont have your 'client_secret.json' file or it is in wrong place.
Scenario 1 - you dont have 'client_secret.json' file
This file is used by API to automatically verify that you are you. With this all API calls are made by your behalf. To get this file:
go to Google API console
open your project (or create new one)
click "Enable APIs and services" to find and enable Google Slides API
click "Credentials" in left menu, and then "Create credentials" -> "oAuth client ID"
choose Web application, accept all windows
now you should see new credentials on list, you can click on them and there will be button on top menu named "download JSON", there you will obtain your credentials (which by name are secret so keep them somewhere safe)
Scenario 2 - your 'client_secret.json' file is in wrong place
In this case I can't be very helpful, just try to inspect library to know where it looks for file and put it there (library directory, project root directory, hard to tell).
Let me know if it worked, as Google APIs and their libraries sometimes acts unexpectedly.

How to authenticate LDAP properly?

I am working on a project that must use LDAP authentication. I am using the server at ldap.forumsys.com after finding the link on Stack Overflow to practice before adding to my Flask application.
If I run the ldapsearch bash command inside of my python code I get a whole bunch of usernames (Tesla etc...) and their associated data (there are no password hashes though). I am able to extract the usernames/user-data as shown here:
username = request.form['username']
password = request.form['password']
cmd = "ldapsearch -h ldap.forumsys.com -D cn=read-only-admin,dc=example,dc=com -w" + os.environ['LDAP_PWD'] + " -b dc=example,dc=com"
ldap_query = os.popen(cmd).read()
user_str = re.sub("\n", "", ldap_query)
users = user_str.split("#")
user_data = ""
for line in users:
if username in line:
user_data = line
break
But then I realized that I LDAP is not the same as a database. I was hoping to find password hashes that I could use to authenticate a user's login information.
So then I tried the python-ldap3 module:
>>> conn = Connection(server, 'uid=tesla,dc=example,dc=com', 'password', auto_bind=True)
>>> conn.bound
True
>>> conn.entries
[]
Unfortunately I can't seem to get any data returned in the list after calling conn.entries.
I can see that the ldap3 module binded the connection. Does the ldapsearch command bind as well? If there are no password hashes, how should I authenticate the username/password entered by the user on the client side?
Thank you all very much.
If the statement...
conn.bound == True
Then the connection has been authenticated via LDAP

Resources