I have set up a VM and I am trying to access different API endpoints such as:
POST https://cloudresourcemanager.googleapis.com/v1/projects/{resource}:testIamPermissions
defined here https://cloud.google.com/resource-manager/reference/rest/v1/projects/testIamPermissions
However, when I run this as part of a python script I get a 401 error with the message:
API keys are not supported by this API. Expected OAuth2 access token or other authentication credentials that assert a principal. See https://cloud.google.com/docs/authentication
I tried enabling OAuth but didn't get any token that I could use in my Python script:
import requests
url = "https://cloudresourcemanager.googleapis.com/v1/projects/{resource}:testIamPermissions"
payload = {
"foo": [
"bar"
]
}
headers = {
'Content-Type': 'application/json'
}
response = requests.post(url, json=payload, headers=headers)
Related
When following this guide to create a model-driven power app using code, what steps do I need to take to successfully make this post request below, which is a replication of the first one in the linked docs. I am currently getting a status of 401.
import requests
url = "https://<OrganizationURI>.api.crm.dynamics.com/api/data/v9.0/appmodules"
header = {
"Content-Type": "application/json",
"OData-MaxVersion": "4.0",
"OData-Version": "4.0",
"Accept": "application/json"
}
data = {
"name": "SDKTestApp",
"uniquename":"SDKTestApp",
"webresourceid":"953b9fac-1e5e-e611-80d6-00155ded156f"
}
response = requests.post(url, headers=header, json=data)
print(response.status_code)
print(response.json())
The guide talks about basic payload for that endpoint to work. That will work as is when the code is running inside Dynamics CRM/Model driven powerapp.
For outside code execution, we need token by using client Id and secret. Before that you have to register in the AAD app registration. You can refer this SO post.
I'm trying to test out some AWS APIs that are protected by Cognito. I found the first part on how to get the Json token but I can't figure out how to use the token correctly so I can authenticate on the API.
Here's my code :
import boto3 as boto3;
import requests
username='test#gmail.com'
password='test1234567'
client = boto3.client('cognito-idp')
response = client.initiate_auth(
AuthFlow='USER_PASSWORD_AUTH',
AuthParameters={
"USERNAME": username,
"PASSWORD": password,
},
ClientId='12121212121212',
)
token = response['AuthenticationResult']['AccessToken']
#print("Log in success")
#print("Access token:", response['AuthenticationResult']['AccessToken'])
#print("ID token:", response['AuthenticationResult']['IdToken'])
url = 'https://XXXXXXXX.execute-api.eu-west-1.amazonaws.com/Prod/incidents'
#print('url:', url)
#response = requests.get(url, headers={'authorization': token })
#print('GET:', response.status_code)
head = {'Authorization': token}
response = requests.get(url, headers=head)
print(response.content)
I'm getting the following error message :
b'{"message":"Authorization header requires \'Credential\' parameter. Authorization header requires \'Signature\' parameter. Authorization header requires \'SignedHeaders\' parameter. Authorization header requires existence of either a \'X-Amz-Date\' or a \'Date\' header. Authorization=
Ok so I found the problem and it's working fine now, 2 things were wrong :
The endpoint was wrong - AWS doesn't send a correct error message (!)
The request has to be sent with response['AuthenticationResult']['IdToken']
Please make sure you have selected Cognito or IAM in your API Gateway. From the error message it seems you have selected IAM for protecting the API.
Check the Authorization header's name which you configured for your Cognito Authorizer. You need to use same header name while passing the Cognito token.
If you have configured OAuth scopes in API Gateway side, then you must use access token. And no scope is configured then you can use ID token for authorization.
That said, you can try from Postman application for testing purpose.
I want to do an API call using request of my user in Calendly like Documentation but I can't do it. I don't know if I need something else in my code, thanks.
import requests, json
api_key = 'aaaaaaaaa'
header = {
'Authorization' : api_key
}
response = requests.get('https://api.calendly.com/users/me/', headers= header)
print(response)
print(response.json())
I'm getting a 401 response:
<Response [401]> {'title': 'Unauthenticated', 'message': 'The access token is invalid'}
I suspect you're trying to use the API Key for API v2. The API Key only works with Calendly's legacy API v1. API v2 supports the following two authorization schemes:
OAuth authorization code flow, or
Personal Access Tokens.
See developer.calendly.com/getting-started for more details.
If you are using a personal token with the API v2, you need to prepend Bearer before your token.
Example:
header = {
'Authorization': f'Bearer {api_key}'
}
Source:
https://calendly.stoplight.io/docs/api-docs/YXBpOjM5NQ-calendly-api
I'm currently using the Python Requests module to add videos to a playlist created by me. On the docs for playlistItems.insert, it says authorization is required with one of three possible scopes. I have created an OAUTH2.0 credential token in my project's credential panel and set the scope correctly. Currently I'm trying to pass the credential as follows:
payload = {
'access_token': [My Client ID],
'part': 'snippet'}
new_vid = requests.post(f'{base_url}playlistItems', params=payload)
When executing the code, I get the following error message:
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project."
Am I passing the authorization token in the correct place, or should I be passing it somewhere else in the POST request?
You can pass the Authorization token as a header parameter. Check the example below:
import requests
headers = {
'Authorization': 'Bearer [YOUR_ACCESS_TOKEN]',
'Accept': 'application/json',
'Content-Type': 'application/json',
}
params = (
('key', '[YOUR_API_KEY]'),
('part','snippet')
)
response = requests.post('https://youtube.googleapis.com/youtube/v3/playlistItems', headers=headers, params=params)
I'm trying to make a Python webapp write to Firebase DB using HTTP API (I'm using the new version of Firebase presented at Google I/O 2016).
My understanding so far is that the specific type of write I'd like to accomplish is made with a POST request to a URL of this type:
https://my-project-id.firebaseio.com/{path-to-resource}.json
What I'm missing is the auth part: if I got it correctly a JWT should be passed in the HTTP Authorization header as Authorization : Bearer {token}.
So I created a service account, downloaded its private key and used it to generate the JWT, added it to the request headers and the request successfully wrote to Firebase DB.
Now the JWT has expired and any similar request to the firebase DB are failing.
Of course I should generate a new token but the question is: I wasn't expecting to handle token generation and refresh myself, most HTTP APIs I'm used to require just a static api key to be passed in the request so my webapps could be kept relatively simple by just adding the stati api key string to the request.
If I have to take care of token generation and expiration the webapp logic needs to become more complex (because I'd have to store the token, check if it is still valid and generate a new one when not), or I could just generate a new token for every request (but does this really make sense?).
I'd like to know if there's a best practice to follow in this respect or if I'm missing something from the documentation regarding this topic.
Thanks,
Marco
ADDENDUM
This is the code I'm currently running:
import requests
import json
from oauth2client.service_account import ServiceAccountCredentials
_BASE_URL = 'https://my-app-id.firebaseio.com'
_SCOPES = [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/firebase.database'
]
def _get_credentials():
credentials = ServiceAccountCredentials.from_json_keyfile_name('my_service_account_key.json', scopes=_SCOPES)
return credentials.get_access_token().access_token
def post_object():
url = _BASE_URL + '/path/to/write/to.json'
headers = {
'Authorization': 'Bearer '+ _get_credentials(),
'Content-Type': 'application/json'
}
payload = {
'title': title,
'message': alert
}
return requests.post(url,
data=json.dumps(payload),
headers=headers)
Currently for every request a new JWT is generated. It doesn't seem optimal to me. Is it possible to generate a token that doesn't expire?
Thanks for the code example. I got it working better by using the credentials.authorize function which creates an authenticated wrapper for http.
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)