Authenticate to azure ad with JWT python sdk - python

I need to authenticate to Azure AD to perform REST API calls.
I'm using Azure Python SDK (https://github.com/Azure/azure-sdk-for-python) for that.
I have another code that returns me the JWT (JSON Web Token) of the user.
How can I connect with this JWT?
I try to look here https://learn.microsoft.com/en-us/azure/developer/python/azure-sdk-authenticate?tabs=cmd
but I didn't find something useful

To call the REST API secured by azure ad, just make an API call with python, pass the token you got to the request header.
As you don't mention the specific API you want to call, here is just an approximate sample, change the url to the API you want and change requests.get to the method you want, there are maybe other headers and bodies depend on the specific API, the access_token is the token you should pass.
import requests
url = 'https://management.azure.com/subscriptions/{subscription-id}/providers/Microsoft.Network/virtualnetworks?api-version=2015-06-15'
headers = {'Content-Type': 'application/json',
'Authorization': 'Bearer ' + access_token}
response = requests.get(url=url,headers = headers)
print(response.status_code)
print(response.text)
Note: You don't provide the code you got the token, I don't know if it is correct, please make sure the audience of the token is correct and has the permission to call the corresponded API, otherwise you will get an error.
Reference:
Making a request to a RESTful API using python
How to make Raw REST Call for Azure using Python

Related

How to create a work item in python using either TFSAPI or requests, ..etc

AM currently writing a rest api python script to interact with azure devops and I wanted to create a work item but am getting 401 or 404 errors. I followed the url query to do a post but I seem not to find the solution.
You can refer this official Azure DevOps Python API doc.
It contains Python APIs for interacting with and managing Azure
DevOps. These APIs power the Azure DevOps Extension for Azure CLI. To
learn more about the Azure DevOps Extension for Azure CLI, visit the
Microsoft/azure-devops-cli-extension repo.
Here is some example code for creating work item in python.
Besides, it is supported to use requests to call Azure DevOps REST API. In this way, you need to create a personal access token (PAT) first. (Make sure you select the correct scope, in your scenario at least have the create work item permission).
Then you can use the PAT to create the basic auth header, and make the request:
import requests
import base64
pat = 'tcd******************************tnq'
authorization = str(base64.b64encode(bytes(':'+pat, 'ascii')), 'ascii')
headers = {
'Accept': 'application/json-patch+json',
'Authorization': 'Basic '+authorization
}
url = "https://dev.azure.com/fabrikam/{project}/_apis/wit/workitems/${type}?api-version=6.0"
payload = "[\n {\n \"op\": \"add\",\n \"path\": \"\/fields\/System.Title\",\n \"from\": null,\n \"value\": \"Sample task\"\n }\n]"
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)

How can I test AWS Cognito protected APIs in 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.

Can't retrieve access token for oauth

I'm trying to implement OAuth for an application that retrieves data from our JIRA server via the REST API. I am able to construct and use an authorization url, and get a message indicating that I have successfully authorized my application when I use it. However, when I then try to request the access-token, I always get response code 401, with content 'oauth_problem=token_rejected'.
I am using Python 3, and have pulled apart the code in the 'oauthdance' function within jirashell to see where the breakdown is happening. I'm not using a callback uri, so I specified 'oob' as the callback and can see the verification string in my browser after I authorize the application.
oauth = OAuth1(consumer_key,
signature_method=SIGNATURE_RSA, rsa_key=key_cert_data, resource_owner_key=request_token, resource_owner_secret=request_token_secret, verifier=<string copied from browser>
)
r = requests.post(
server + '/plugins/servlet/oauth/access-token', verify=verify, auth=oauth)
I would expect this code to retrieve the access token, but instead it's returning the 401 response. The request_token and request_token_secret appear to be valid and were retrieved via the request-token servlet.
I found the answer here: https://community.developer.atlassian.com/t/java-oauth-example-does-not-work/3779/2
The consumer key used with OAuth is case-sensitive. I changed it to exactly match the value entered by our admin in JIRA and got an access token.

How to get oauth2-token for Google Analytics Reporting API (REST method) in Python

I want to route my Google Analytics Reporting API request (code will be in AWS Lambda) through a gateway which accepts a REST endpoint only. Since I cant use the Client package method in my interaction with the gateway, I need to query the API as a REST-ful endpoint.
The official document says this (Link) :
Authorization: Bearer {oauth2-token}
GET https://www.googleapis.com/analytics/v3/data/ga
?ids=ga:12345
&start-date=2008-10-01
&end-date=2008-10-31
&metrics=ga:sessions,ga:bounces
I do not know to create the oauth2-token in Python. I have created a service account and have the secrets_json which includes the client id and secret key.
Then client package method as given in this link works. But I need the Rest method only!
Using these, how can I create the oauth2-token ?
You can use Oauth2 for this I have done it in the past but you will need to monitor it. You will need to authorize this code once and save the refresh token. Refresh tokens are long lived they normally dont expire but your code should be able to contact you if it does so that you can authorize it again. If you save the refresh token you can use the last step at any time to request a new access token.
Oauth2 is basicly built up into three calls. I can give you the HTTP calls i will let you work out the Python Google 3 Legged OAuth2 Flow
Authencation and authorization
The first thing you need is the permission of the user. To get that you build a link on the authorization server. This is a HTTP get request you can place it in a normal browser window to test it.
GET https://accounts.google.com/o/oauth2/auth?client_id={clientid}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code
Note on redirect uri. If you are running this on a server or something then use urn:ietf:wg:oauth:2.0:oob it basicly tells the server to return the code back where it came from other wise if you are hosing on a website you can supply a url to the page that will be handling the response.
If the user accepts the above then you will have an authorization code.
Exchange code
What you need to do next is exchange the authorization code returned by the above response and request an access token and a refresh token. THis is a http post call
POST https://accounts.google.com/o/oauth2/token
code=4/X9lG6uWd8-MMJPElWggHZRzyFKtp.QubAT_P-GEwePvB8fYmgkJzntDnaiAI&client_id={ClientId}&client_secret={ClientSecret}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code
The body parameter should be as i have shown separated by & and the content type of the request is application/x-www-form-urlencoded
Responce
{
"access_token" : "ya29.1.AADtN_VSBMC2Ga2lhxsTKjVQ_ROco8VbD6h01aj4PcKHLm6qvHbNtn-_BIzXMw",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "1/J-3zPA8XR1o_cXebV9sDKn_f5MTqaFhKFxH-3PUPiJ4"
}
The access token can be used in all of your requests to the api by adding either an authorization header bearer token with the access token or by sending access_token= as your parameter in your requests.
Refresh access token
Refresh tokens are long lived they should not expire they can so you code should be able to handle that but normally they are good forever. Access tokens are only valid for one hour and you will need to request a new access token.
POST https://accounts.google.com/o/oauth2/token
client_id={ClientId}&client_secret={ClientSecret}&refresh_token=1/ffYmfI0sjR54Ft9oupubLzrJhD1hZS5tWQcyAvNECCA&grant_type=refresh_token
response
{
"access_token" : "ya29.1.AADtN_XK16As2ZHlScqOxGtntIlevNcasMSPwGiE3pe5ANZfrmJTcsI3ZtAjv4sDrPDRnQ",
"token_type" : "Bearer",
"expires_in" : 3600
}

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.

Categories

Resources