Add (AWS Signature) Authorization to python requests - python-3.x

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')

Related

Get a SAS on a azure snapshot - Using Azure Compute API

I am trying to generate the SAS URI for one of the snapshot exist on resource group using microsoft provided API.
Below is the snippet code:
url = f"https://management.azure.com/subscriptions/{subscription_id}/resourceGroups/{target_resource_group}/providers/Microsoft.Compute/snapshots/{snap_name}/beginGetAccess"
headers = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'}
params = {'api-version': '2021-12-01'}
body= {
"access": "Read",
"durationInSeconds": 3000
}
json_body= json.dumps(body, indent=2)
accessSAS=requests.post(url, headers=headers, params=params, data=json_body, verify=False)
But I am receiving the response as <Response [202]>.
Could anyone help me with the issue.
Response 202 means that Azure accepts your request but it is handling your request. It is an asynchronous operation. Therefore, the response header will give you another url for getting the result. You can refer the following link to get what you want.
https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/async-operations

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)

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)

Error calling CF API login one time passcode

I am working with the CF API RESTful services. Trying to get an access token from cloud foundry's UAA API using https://login..../oauth/token web method.
I have verified that headers & body content is correct, but calling the api always returns a 400 error code with message missing grant type.
I have implemented this call in Objective-C, Swift & now Python. All tests return the same result. Here is my code example in Python:
import json
import requests
import urllib
params = {"grant_type": "password",
"passcode": "xxx"
}
url = "https://login.system.aws-usw02-pr.ice.predix.io/oauth/token"
headers = {"Authorization": "Basic Y2Y6", "Content-Type": "application/json", "Accept": "application/x-www-form-urlencoded"}
encodeParams = urllib.parse.urlencode(params)
response = requests.post(url, headers=headers, data=encodeParams)
rjson = response.json()
print(rjson)
Each time I run this, I get the response
error invalid request, Missing grant type
Any help would be greatly appreciated.
Your code mostly worked for me, although I used a different UAA server.
I had to make only one change. You had the Accept and Content-Type headers flipped around. Accept should be application/json because that's the format you want back, and Content-Type should be application/x-www-form-urlencoded because that's the format you are sending.
See the API Docs for reference.
import json
import requests
import urllib
import getpass
UAA_SERVER = "https://login.run.pivotal.io"
print("go to {}/passcode".format(UAA_SERVER))
params = {
"grant_type": "password",
"passcode": getpass.getpass(),
}
url = "https://login.run.pivotal.io/oauth/token"
headers = {
"Authorization": "Basic Y2Y6",
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json"
}
encodeParams = urllib.parse.urlencode(params)
response = requests.post(url, headers=headers, data=encodeParams)
rjson = response.json()
print(json.dumps(rjson, indent=4, sort_keys=True))
I made a couple other minor changes, but they should affect the functionality.
Use getpass.getpass() to load the passcode.
Set the target server as a variable.
Pretty print the JSON response.
The only other thing to note, is that the OAuth2 client you use must be allowed to use the password grant type. It looks like you're using the same client that the cf cli uses, so if your UAA server is part of a standard Cloud Foundry install that is likely to be true, but if it still doesn't work for you then you may need to talk with an administrator and make sure the client is set up to allow this.

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