How to authenticate private API token in Python to access RightSignature - python

I'm new to Python and attempting to write a script that connects to RightSignature API using a private API Token. The documentation says to use the Private API Token, along with the Client ID and Client Secret to sign API requests. This should be returning information about the authenticated RightSignature User. All the private info is stored in a .env file.
Here's what I have so far...
from flask import Flask, request, jsonify
import os
import requests
from dotenv import load_dotenv
API_HOST = "api.rightsignature.com"
load_dotenv()
API_TOKEN = os.environ.get("API_TOKEN")
CLIENT_ID = os.environ.get("client_id")
CLIENT_SECRET = os.environ.get("client_secret")
headers = {
"private-api-key" : API_TOKEN,
"client-id" : CLIENT_ID,
"client-secret" :CLIENT_SECRET
}
url = "https://{}/public/v2/me".format(API_HOST)
response = requests.get(url, headers=headers)
print(response.text)
I get the following error if I run this...
{"error":"invalid_token","error_description":null}
Any help would be greatly appreciated!!!

Related

Azure rest api with Python

I am new to Azure. I need to set up an automation script to list all Ips in azure using Azure Rest APi in Python. However i couldnt been able to get any result from the API url I am passing to the request.
I am following this https://learn.microsoft.com/en-us/rest/api/virtualnetwork/public-ip-addresses/list-all#code-try-0
In code block, I have tried using requests
import requests
apijson = requests.get("https://management.azure.com/subscriptions/9540b342-9f94-4dd9-9eca-0698dda0107c/providers/Microsoft.Network/publicIPAddresses?api-version=2021-05-01"
I know I need to setup Oauth/authentication but I don't know what I need to declare or pass any token from my script
I know I need to setup Oauth/authentication but I don't know what I need to declare or pass any token from my script
You can declare/pass token, for example:
import sys
import requests
import json
import time
test_api_url = "Add URL which you want to test"
#function to obtain a new OAuth 2.0 token from the authentication server
def get_new_token():
auth_server_url = "https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token'"
client_id = 'XXXX-XXXX-XXXX'
client_secret = 'XXXX'
token_req_payload = {'grant_type': 'client_credentials'}
token_response = requests.post(auth_server_url,
data=token_req_payload, verify=False, allow_redirects=False,
auth=(client_id, client_secret))
if token_response.status_code !=200:
print("Failed to obtain token from the OAuth 2.0 server", file=sys.stderr)
sys.exit(1)
print("Successfuly obtained a new token")
tokens = json.loads(token_response.text)
return tokens['access_token']
token = get_new_token()
while True:
api_call_headers = {'Authorization': 'Bearer ' + token}
api_call_response = requests.get(test_api_url, headers=api_call_headers,
verify+False)
if api_call_response.status_code == 401:
token = get_new_token()
else:
print(api_call_response.text)
time.sleep(30)
You can refer to How to authenticate and authorize Python applications on Azure, Azure AD Authentication Python Web API and Protect an API by using OAuth 2.0 with Azure Active Directory and API Management

Google Cloud Run: Calling from outside GCP

I'm trying to access a secure cloud run service. If I try from my machine with the SDK it works fine:
curl --header "Authorization: Bearer $(gcloud auth print-identity-token)"
However, I can not get it to work using the Python API using the same service account, I've tried using google-auth to get an access token but that gives me a 401 authentication error. This is the code I am using to try to get a token:
import google.auth
import google.auth.transport.requests
scopes = ['https://www.googleapis.com/auth/cloud-platform']
creds, projects = google.auth.default(scopes=scopes)
auth_req = google.auth.transport.requests.Request()
creds.refresh(auth_req)
# then using creds.token
Looking at the docs: https://cloud.google.com/run/docs/authenticating/service-to-service#calling_from_outside_gcp it says to follow the sample code here: https://cloud.google.com/iap/docs/authentication-howto#iap_make_request-python I can't seem to follow the guide as it says to enable IAP but it seems that IAP is only for app engine and not cloud run?
Has anyone go any advice on this one?
Thanks
OK it seems that there is an IDTokenCredentials class that works for this as it uses Open ID Connect ID Tokens instead of OAuth 2.0 Access Tokens:
https://google-auth.readthedocs.io/en/latest/reference/google.oauth2.service_account.html
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
service_url = 'example.com'
key_file = 'key.json'
credentials = service_account.IDTokenCredentials.from_service_account_file(
key_file, target_audience=service_url)
authed_session = AuthorizedSession(credentials)
response = authed_session.get(service_url)
It's confusing as I don't see it in the docs and it's leading me to something else about IAP which I don't think is working with Cloud Run.
If you still want to obtain your ID token and not use method from Dan's response there is an updated code:
import requests
import google.auth
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
service_url = 'example.com'
key_file = 'key.json'
credentials = service_account.IDTokenCredentials.from_service_account_file(
key_file, target_audience=service_url)
request = google.auth.transport.requests.Request()
credentials.refresh(request)
token = credentials.token
print('ID Token:', token)

OAuth2 authorization for API in Python

I'm trying to use OAuth2 authorization for an API through the company Manheim using Python 3.
The documentation states "The 'Client Credentials' and 'Resource Owner' grant types are both supported now and required changes to request a token are detailed here." Here is the documentation to the API: http://developer.manheim.com/#/authentication
I've used the following link as a guide but to no avail:
https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow
They've provided me with a client id and client secret. I'm receiving the following error:
MissingTokenError: (missing_token) Missing access token parameter.
I've tried this:
from oauthlib.oauth2 import BackendApplicationClient
client_id = 'my_id'
client_secret = 'my_secret'
token_url = 'https://sandbox.api.manheim.com/oauth2/token.oauth2'
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=token_url,
client_id=client_id,client_secret=client_secret)
I've also tried this:
from oauthlib.oauth2 import BackendApplicationClient
from requests.auth import HTTPBasicAuth
client_id = 'my_id'
client_secret = 'my_secret'
token_url = 'https://sandbox.api.manheim.com/oauth2/token.oauth2'
auth = HTTPBasicAuth(client_id, client_secret)
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=token_url, auth=auth)
I've tried other techniques but have had no success. What am I doing wrong? What do I need to do access the API?
I appreciate any and all help!
RESULT:
Fixed it myself by reaching out to the developer team managing the API. I was using the wrong endpoint.
I changed token_url to the following:
token_url = 'https://api.manheim.com/oauth2/token.oauth2'

Flask session won't allow assignment from urlfetch content - Internal Server Error

I have a Python app running on Google App Engine. I am trying to perform an Oauth 2 authentication without using oauth libraries.
I need a session to store the information returned from the Google auth code (access token) and send it to the next request. When I try to store the JSON into a flask session key, my app goes to an Internal Server Error with no debug info. My code is practically a copy-paste from Google's HTTP Rest example in their Oauth2 for web server apps documentation (link commented in code).
import logging
import flask
from flask import render_template, session
import json
import urllib
from google.appengine.api import urlfetch
#Code from https://developers.google.com/identity/protocols/OAuth2WebServer
app = flask.Flask(__name__)
CLIENT_ID = '[].apps.googleusercontent.com'
CLIENT_SECRET = '[]'
SCOPE = 'email'
REDIRECT_URI = 'https://[].appspot.com/oauthcallback'
#check for last oauth step, if not go to intermediate steps
#app.route('/')
def index():
if 'credentials' not in flask.session:
return flask.render_template('index.html')
credentials = json.loads(flask.session['credentials'])
if credentials['expires_in'] <= 0:
return flask.redirect(flask.url_for('oauthcallback'))
else:
headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])}
req_uri = 'https://www.googleapis.com/oauth2/v2/userinfo'
r = requests.get(req_uri, headers=headers)
return r.text
#ask user to sign in, send code to googleapi to get token
#app.route('/oauthcallback')
def oauthcallback():
if 'code' not in flask.request.args:
auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id={}&redirect_uri={}&scope={}').format(CLIENT_ID, REDIRECT_URI, SCOPE)
return flask.redirect(auth_uri)
else:
auth_code = flask.request.args.get('code')
data = {'code': auth_code, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'redirect_uri': REDIRECT_URI, 'grant_type': 'authorization_code'}
r = urlfetch.fetch("https://www.googleapis.com/oauth2/v4/token", payload=data, method="POST")
#return r.content #prints json
flask.session['credentials'] = r.content #breaks here
return flask.redirect(flask.url_for('index'))
if __name__ == '__main__':
import uuid
app.secret_key = str(uuid.uuid4())
app.debug = True
app.run()
Did you enable the redirect URI?
https://developers.google.com/api-client-library/python/auth/web-app
Create authorization credentials
Any application that uses OAuth 2.0 to access Google APIs must have authorization credentials that identify the application to Google's OAuth 2.0 server. The following steps explain how to create credentials for your project. Your applications can then use the credentials to access APIs that you have enabled for that project.
Open the Credentials page in the API Console.
Click Create credentials > OAuth client ID.
Complete the form. Set the application type to Web application. Applications that use languages and frameworks like PHP, Java, Python, Ruby, and .NET must specify authorized redirect URIs. The redirect URIs are the endpoints to which the OAuth 2.0 server can send responses.
For testing, you can specify URIs that refer to the local machine, such as http://localhost:8080. With that in mind, please note that all of the examples in this document use http://localhost:8080 as the redirect URI.

Fail to authorize using ServiceAccountCredentials for calls to Firebase (REST API / python)

I always get 401 error trying to fetch Firebase resource and passing access token. I cannot get what am I doing wrong.
So I follow this manual: I created service account, then create ServiceAccountCredentials object, passing scope https://www.googleapis.com/auth/firebase. Then I get token from created object and pass it as access_token query parameter, as stated in docs, trying fetch data from my Firebase DB. But I keep getting 401 error (unauthorized). Token, by the way, seems to be invalid if check in tool like jsonwebtoken (probably I do something wrong there / provide incorrect secret?).
So, my code is like this:
import httplib2
from oauth2client.service_account import ServiceAccountCredentials
credentials = ServiceAccountCredentials.from_json_keyfile_name('/path/auth.json', scopes=['https://www.googleapis.com/auth/firebase'])
token = credentials.get_access_token().access_token
http = httplib2.Http()
result = http.request('https://my-project.firebaseio.com/srv.json?access_token=%s' % token)
And result body always is {"error" : "Unauthorized request."} along with 401 HTTP status code.
I think your scopes were not sufficient. Here is a end to end example I got working using credentials and the credentials.authorize http wrapper
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
import json
_BASE_URL = 'https://my-app-id.firebaseio.com'
_SCOPES = [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/firebase.database'
]
# Get the credentials to make an authorized call to firebase
credentials = ServiceAccountCredentials.from_json_keyfile_name(
_KEY_FILE_PATH, scopes=_SCOPES)
# Wrap the http in the credentials. All subsequent calls are authenticated
http_auth = credentials.authorize(Http())
def post_object(path, objectToSave):
url = _BASE_URL + path
resp, content = http_auth.request(
uri=url,
method='POST',
headers={'Content-Type': 'application/json'},
body=json.dumps(objectToSave),
)
return content
objectToPost = {
'title': "title",
'message': "alert"
}
print post_object('/path/to/write/to.json', objectToPost)

Categories

Resources