OneLogin credential not working on API-V2 - onelogin

I have credentials with scope 'Manage users'.
I manage to create access_token but ​credentials work for API v1 (/api/1/users) but not for v2 (/api/2/users).
The error message I get is: {"message":"Unauthorized","name":"UnauthorizedError","statusCode":401}
I've tried it from python and postman.
Anyone working with users V2 and managed to make it work?
r = requests.post(
url='https://api.us.onelogin.com/auth/oauth2/v2/token',
auth=(CLIENT_ID, CLIENT_SECRET),
json={'grant_type': 'client_credentials'}
)
response = r.json()
auth_token = response['access_token']
r = requests.get(
url='https://api.us.onelogin.com/api/1/users',
headers= {'Authorization': f'bearer:{auth_token}'}
)
print(r.status_code)
>> 200
r = requests.get(
url='https://api.us.onelogin.com/api/2/users',
headers= {'Authorization': f'bearer:{auth_token}'}
)
print(r.status_code)
>>401

I was able to reproduce your issue using Postman.
Your Input
Authorization:bearer:<access_token>
Correct Input:
Authorization:bearer <access_token>
Notice the whitespace between bearer and <access_token>. I am assuming you downloaded OneLogin provided Postman Collection. With their Collection, it doesn't work.

Related

Add (AWS Signature) Authorization to python requests

I am trying to make a GET request to an endpoint which uses AWS Authorization. I made request using postman, It works. But when i tried following method in python, it's giving error.
CODE
url = 'XXX'
payload = {}
amc_api_servicename = 'sts'
t = datetime.utcnow()
headers = {
'X-Amz-Date': t.strftime('%Y%m%dT%H%M%SZ'),
'Authorization': 'AWS4-HMAC-SHA256 Credential={}/{}/{}/{}/aws4_request,SignedHeaders=host;x-amz-date,Signature=3ab1067335503c5b1792b811eeb84998f3902e5fde925ec8678e0ff99373d08b'.format(amc_api_accesskey, current_date, amc_api_region, amc_api_servicename )
}
print(url, headers)
response = requests.request("GET", url, headers=headers, data=payload)
ERROR
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method.
Please point me in the right direction.
import boto3
client = boto3.client('sts')
respone=client.assume_role(RoleArn='your i am urn',RoleSessionName='PostmanNNN')

How do I get id_token to properly load in Cloud Run?

I have a Django app that I have been working on. When I run it locally it runs perfectly. When I run it in a container using Cloud Run I get the following error:
'Credentials' object has no attribute 'id_token'
Here is the offending code (payload is a dictionary object):
def ProcessPayload(payload):
# Get authorized session credentials
credentials, _ = google.auth.default()
session = AuthorizedSession(credentials)
credentials.refresh(Request(session))
# Process post request
headers = {'Authorization': f'Bearer {credentials.id_token}'}
response = requests.post(URL, json=payload, headers=headers)
In my local environment, the refresh properly loads credentials with the correct id_toled for the needed header, but for some reason when the code is deployed to Cloud Run this does not work. I have the Cloud run instance set to use a service account so it should be able to get credentials from it. How do I make this work? I have googled until my fingers hurt and have found no viable solutions.
When executing code under a Compute Service (Compute Engine, Cloud Run, Cloud Functions), call the metadata service to obtain an OIDC Identity Token.
import requests
METADATA_HEADERS = {'Metadata-Flavor': 'Google'}
METADATA_URL = 'http://metadata.google.internal/computeMetadata/v1/' \
'instance/service-accounts/default/identity?' \
'audience={}'
def fetch_identity_token(audience):
# Construct a URL with the audience and format.
url = METADATA_URL.format(audience)
# Request a token from the metadata server.
r = requests.get(url, headers=METADATA_HEADERS)
r.raise_for_status()
return r.text
def ProcessPayload(payload):
id_token = fetch_identity_token('replace_with_service_url')
# Process post request
headers = {'Authorization': f'Bearer {id_token}'}
response = requests.post(URL, json=payload, headers=headers)
The equivalent curl command to fetch an Identity Token looks like this. You can test from a Compute Engine instance:
curl -H "metadata-flavor: Google" \
http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=URL
where URL is the URL of the service you are calling.
Authentication service-to-service
I have seen this metadata URL shortcut (for Cloud Run), but I have not verified it:
http://metadata/instance/service-accounts/default/identity?audience=URL
So, after much playing around I found a solution that works in both places. Many thanks to Paul Bonser for coming up with this simple method!
import google.auth
from google.auth.transport.requests import AuthorizedSession, Request
from google.oauth2.id_token import fetch_id_token
import requests
def GetIdToken(audience):
credentials, _ = google.auth.default()
session = AuthorizedSession(credentials)
request = Request(session)
credentials.refresh(request)
if hasattr(credentials, "id_token"):
return credentials.id_token
return fetch_id_token(request, audience)
def ProcessPayload(url, payload):
# Get the ID Token
id_token = GetIdToken(url)
# Process post request
headers = {'Authorization': f'Bearer {id_token}'}
response = requests.post(url, json=payload, headers=headers)

Python3 - Get Request with Secret

I am trying to send a get request to Airtable to get metadata but I keep getting errors.
I have tried the below.
base_schema_url = 'https://api.airtable.com/v0/meta/bases/BaseId(replaced this)/tables'
secret_meta_token = '123'
#attempt 1
r = requests.get(base_schema_url, headers={'Authorization': secret_meta_token})
print(r.text)
#attempt 2
r = requests.get(base_schema_url,
headers={'Content-Type':'application/json',
'Authorization': 'Bearer {}'.format(secret_meta_token)})
print(r.text)
#attempt 3
header = {'PRIVATE-TOKEN': secret_meta_token}
r = requests.get(base_schema_url, headers=header)
print(r.text)
I have a feeling it's because I need to pass in the user API + the Meta token but I'm not too sure how to do it.
The metadata API uses a separate key that you need to send a formal request to the Airtable team by registering at the link provided at the top of the page.
import requests
user_account_api = xxx
meta_api = xxx
base_id = xxx
headers = {
"Authorization":f"Bearer {user_account_api}",
"x-airtable-client-secret": meta_api
}
response = requests.get(f"https://api.airtable.com/v0/meta/bases/{base_id}/tables", headers=headers)
print(response.text)

Authenticating to an API using Python3 with a consumer key and consumer secret

I'm trying to login to an API to retrieve an access token using a consumer secret and key. Following several threads on stackoverflow, I've gotten this far:
consumer = "<myconsumerkey>:<myconsumersecret>"
b64val = base64.b64encode(consumer.encode()).decode()
headers = {"Authorization": "Basic %s" % b64val, "Content-Type": 'application/x-www-form-urlencode'}
response = requests.post('https://mysite/token', headers=headers, verify=False)
This always throws a 415 error. I've read the requests api documentation so many times I'm going crazy where is my malfunction here?
I do not know why, but adding
data = {'grant_type': 'client_credentials'}
to the post worked. The code is:
def login():
consumer = consumer_key + ":" + consumer_secret
b64val = base64.b64encode(consumer.encode()).decode()
headers = {"Authorization": "Basic %s" % b64val}
data = {'grant_type': 'client_credentials'}
response = requests.post('https://mywebsite:8243/token', headers=headers, data=data)

Paylocity API Access Token

I have been trying to retreive the access token for the paylocity API. I am able to get it through postman with the client id and client secret however when I try and retrieve it with Python I get the message {"error":"invalid_client"}. This is the code that I am using
import json
import base64
import requests
url = "https://api.paylocity.com/IdentityServer/connect/token"
client_id = ''
client_secret = ''
auth = (f'{client_id}:{client_secret}')
headers = {
'content-type': "application/x-www-form-urlencoded",
'Authorization': f"Basic {auth}"
}
body = "grant_type=client_credentials&scope=WebLinkAPI"
response = requests.request("POST", url, data=body, headers=headers)
print (response.text)
In case someone else stumbles on this response, since there are not many search hits for this:
To get the token from Paylocity and call their API:
client_id = {your client id string}
client_secret = {your client secret}
company_id = {your company id from Paylocity dashboard, without leading 'CS'}
prod_auth_url = 'https://api.paylocity.com/IdentityServer/connect/token'
body_params = urllib.parse.urlencode({'grant_type': 'client_credentials','scope':'WebLinkAPI'})
# Requests can use auth= for basic authentication
auth_response = requests.post(prod_auth_url,auth=(client_id, client_secret), data=urllib.parse.urlencode(body_params))
response = json.loads(auth_response.content)
api_call_headers = {'Authorization': 'Bearer ' + response['access_token']}
# Get all employees for a company
empl_response = requests.get(f"https://api.paylocity.com/api/v2/companies/{company_id}/employees/",headers=api_call_headers, verify=False)
pd.DataFrame(json.loads(empl_response.text))
Make sure you're using the client_id and client_secret for your token call, not the company id. It is not necessary to use any OAuth2 libraries to access the API.
for only the token I do:
import requests, json
token_url = "https://apisandbox.paylocity.com/IdentityServer/connect/token"
#client credentials
client_id = 'XXXX'
client_secret = 'XXXXXX'
#step A, B - single call with client credentials as the basic auth header - will return access_token
data = {'grant_type': 'client_credentials', 'scope':'WebLinkAPI'}
access_token_response = requests.post(token_url, data=data, verify=False, allow_redirects=False, auth=(client_id, client_secret))
print(access_token_response.headers)
print (access_token_response.text)
And after that code I recived the Token the same as the PostMan.
you can check: https://developer.byu.edu/docs/consume-api/use-api/oauth-20/oauth-20-python-sample-code
for more information/options.
Try the following with the same variables:
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=url, client_id=client_id, client_secret=client_secret, body=body, headers=headers)

Resources