How can I test AWS Cognito protected APIs in Python? - python

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.

Related

How do I get a DocuSign Monitor API access token

I am trying to get an access token to access the DocuSign Monitor API via the JWT grant method as it states in the documentation for the DocuSign Monitor API. Here is a snippet of my test script:
def create_jwt(self):
epoch_time = int(time.time())
priv_key = self.get_rsa(self.privkey_path)
pub_key = self.get_rsa(self.pubkey_path)
body = {"iss": self.iss,
"iat": epoch_time,
"exp": (epoch_time + 3000),
"aud": 'account-d.docusign.com',
"scope": "monitor"}
encoded = jwt.encode(body, priv_key, algorithm='RS256')
# decoded = jwt.decode(encoded, pub_key, audience='account-d.docusign.com', algorithm='RS256')
return encoded
def request_access_token(self, encoded_token):
url = 'https://account-d.docusign.com/oauth/token'
data = {'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion': encoded_token}
response = requests.post(url=url, data=data)
return response.text
request_access_token returns:
{"error":"invalid_scope"}
As far as I can tell I am following the documentation correctly. Using these functions I am able to successfully generate an access token for other scopes such as signature etc. Is there some problem with developer accounts requesting access to the monitor scope since it is a beta feature? What would a valid request to 'lens.docusign.net/api/v1.0/monitor/organization/{{organizationId}}' look like? I assume one needs to acquire an access token before attempting to make requests to the monitor API? I can't tell where I'm going wrong here. Any help would be greatly appreciated.
So this API is in beta and we have to personally enable your account to use it.
Use this form to submit a request
More information about this new API

Firebase DB HTTP API Auth: When and how to refresh JWT token?

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)

Python Requests - Azure RM API returning 200 status code but 400 in content

I have some code where I am trying to authenticate against Azure's Resource Manager REST API.
import json
import requests
tenant_id = "TENANT_ID"
app_id = "CLIENT_ID"
password = "APP_SECRET"
token_endpoint = 'http://login.microsoftonline.com/%s/oauth2/token' % tenant_id
management_uri = 'https://management.core.windows.net/'
payload = { 'grant_type': 'client_credentials',
'client_id': app_id,
'client_secret': password
}
auth_response = requests.post(url=token_endpoint, data=payload)
print auth_response.status_code
print auth_response.reason
This returns:
200
OK
However, when I print auth_response.content or auth_reponse.text, I get back a 400 HTML error code and an error message.
HTTP Error Code: 400
Sorry, but we’re having trouble signing you in.
We received a bad request.
I am able to get back the correct information using PostMan, however, with the same URI and payload. I used the "Generate Code" option in Postman to export my request to a Python requests script and tried running that. But, I get the same errors.
Anybody have any idea why this is happening?
Only modify your token_endpoint to https Protocols. E.G:
token_endpoint = 'https://login.microsoftonline.com/%s/oauth2/token' % tenant_id.
You can refer to https://msdn.microsoft.com/en-us/library/azure/dn645543.aspx for more details.
Meanwhile, you can leverage Microsoft Azure Active Directory Authentication Library (ADAL) for Python for acquire the access token in a ease.
You should use HTTPS instead of HTTP for token_endpoint, and you should specify API version too. Here is what you should use.
token_endpoint = 'https://login.microsoftonline.com/%s/oauth2/token?api-version=1.0' % tenant_id

Python Requests - Azure Graph API Authentication

I am trying to access the Azure AD Graph API using the Python requests library. My steps are to first get the authorization code. Then, using the authorization code, I request an access token/refresh token and then finally query the API.
When I go through the browser, I am able to get my authorization code. I copy that over to get the access token. However, I've been unable to do the same with a Python script. I'm stuck at the part where I get the authorization code.
My script returns a response code of 200, but the response headers don't include that field. I would've expected the new URL with the code to be in the response headers. I would have also expected a response code of 301.
Does anyone know why my response headers don't have the auth code? Also, given the auth code, how would I pull it out to then get the access/refresh tokens using Python?
My code is below:
import requests
s = requests.Session()
s.auth = (USERNAME, PASSWORD)
# Authorize URL
authorize_url = 'https://login.microsoftonline.com/%s/oauth2/authorize' % TENANT_ID
# Token endpoint.
token_url = 'https://login.microsoftonline.com/%s/oauth2/token' % TENANT_ID
payload = { 'response_type': 'code',
'client_id': CLIENT_ID,
'redirect_uri': REDIRECT_URI
}
request = s.get(authorize_url, json=payload, allow_redirects=True)
print request.headers
It looks that you are implementing with Authorization Code Grant Flow via python requests. As the flow shows, the response of the request of authorize_url will redirect to a SSO page of your AD tenant. After your user login on, it will redirect to the location which set in redirect_uri with code as the URL parameters. E.G. http://localhost/?code=AAABAAAAiL...
And your code seems cannot simply display a html page with JavaScript allowed, so it will not redirect to the login on page.
So you can refer to # theadriangreen’s suggestion to implement with a python web server application.
Otherwise, you can refer to Microsoft Azure Active Directory Authentication Library (ADAL) for Python, which is a python package for acquiring access token from AD and can be easily integrated in your python application.

How to pass 'Authorization' header value in OAuth 2.0 with Google APIs

I am trying to access Google's APIs with OAuth 1.0 and 2.0 in both cases I need to fill Authorization field in the headers with value 'OAuth' followed by access token. I tried following method, but Google throws me an error saying there is problem in Authorization header values. I am using Python-Tornado
additional_headers = {
"Authorization": "OAuth "+GoogleOAuth2Mixin.access_token,
"Accept-Encoding": None
}
h = httputil.HTTPHeaders()
h.parse_line("Authorization: OAuth "+GoogleOAuth2Mixin.access_token)
request = httpclient.HTTPRequest(self._USER_INFO_URL+"?access_token="+GoogleOAuth2Mixin.access_token, method="GET", headers=h)
self.httpclient_instance.fetch(
request,
self.async_callback(callback)
)
I tried using both methods, by passing header 'h' and 'additional_headers', but it doesn't work. What is an accurate method?
I had same problem. It works if 'Bearer ' is included as prefix.
Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42
Thats because it uses account email address as a UID and it calls the userinfo service by default during the authentication flow, so you need to include "userinfo.email" in your scopes list otherwise the authentication flow will raise and exception and fail to return the tokens.
If you are using OAuth 2.0 playground be sure to check "Userinfo-Email" under Select and authorize API's on left bar along with the API you want to use. Hope this helps.

Categories

Resources