I am using python to insert FHIR jsons into Azure API for FHIR. I have deployed Azure api for fhir service and also did a app registration.
My app is not a web application. It just reads the input json and publishes it to FHIR server. And hence, i created Public/Mobile&Desktop applications.
With postman i am able to successfully post a message. However, i would like to do that with my python script. I am struck at fetching Access Token via OAuth2.
I tried the following code and its throwing empty tenant id . When i googled about OAuth2, There are multiple packages like rauth, ADAL, msal. None of them worked for me.
import requests
app_id = <client_id>
token_url = https://login.microsoftonline.com/<tenant_id>/oauth2/token
token_data = {
'resource': 'APP_ID_URL',
'grant_type': 'password',
'client_id': app_id,
'client_secret': client_secret,
'scope':'',
'username':'USERNAME',
'password':'PASSWORD',
}
I am getting 200 response, but it returns an html saying problem signing in the user. Is there a simple way of getting OAuth2 token via python script. I checked other SO posts related to this. Most of the answers are not working for me.
What you are looking to do is client credentials flow, which you can read more about here: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow
For Azure API for FHIR, you want to make a service client (https://learn.microsoft.com/en-us/azure/healthcare-apis/register-service-azure-ad-client-app) and once you have a service client, you need to modify your request to something like (not tested):
For v2.0 of the AAD endpoint (recommended):
import requests
app_id = <client_id>
token_url = https://login.microsoftonline.com/<tenant_id>/oauth2/v2.0/token
token_data = {
'grant_type': 'client_credentials',
'client_id': app_id,
'client_secret': client_secret,
'scope':'https://<yourfhirservice>.azurehealthcareapis.com/.default',
}
For v1.0 (https://learn.microsoft.com/en-us/azure/active-directory/azuread-dev/v1-oauth2-client-creds-grant-flow) you can probably do something like:
import requests
app_id = <client_id>
token_url = https://login.microsoftonline.com/<tenant_id>/oauth2/token
token_data = {
'grant_type': 'client_credentials',
'client_id': app_id,
'client_secret': client_secret,
'resource':'https://<yourfhirservice>.azurehealthcareapis.com',
}