I have two apps both registered on Azure AD:
-APP_1: a web app that runs in flask with SSO through Azure AD
tenant_id = "tenant_id_of_APP_1_and_APP_2"
client_id_app_1 = "app_1"
client_secret_app_1 = "secret_app_1"
-APP_2: another app that makes requests to the first app:
tenant_id = "tenant_id_of_APP_1_and_APP_2"
client_id_app_2 = "app_2"
client_secret_app_2 = "secret_app_2"
the endpoints on the APP_1 are restricted. When the user reaches the web app through the browser he is automatically requested to login, and after he is identified it can navigate any endpoint he has access to otherwise he gets PermissionError.
Now I want to give access to some endpoints to the APP_2, I can get an access_token from azure in this way (I think I'm going something wrong because when I request a token I should specify that is for APP_1, but i cannot find the argument that specifies it):
import requests
# Authenticate and get an access token
auth_url = f'https://login.microsoftonline.com/{tenant_id_of_APP_1_and_APP_2}/oauth2/v2.0/token'
data = {
'grant_type': 'client_credentials',
'client_id': client_id_app_2,
'client_secret': client_secret_app_2,
'scope': 'https://graph.microsoft.com/.default'
}
response = requests.post(auth_url, data=data).json()
access_token = response['access_token']
and then I can make the request to the protected API:
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/octet-stream',
}
x = requests.post("https://localhost:5000/test_api", headers=headers)
response = requests.get("http://localhost:5000/test_api", headers=headers)
What should I do the server (APP_1) when I get such request? I should validate the access_token to verify the user but I cannot decode it with jwt because I keep getting invalid signature:
token = request.headers.get("Authorization").removeprefix("Bearer ")
public_key = get_public_key(token)
decoded = jwt.decode(
token,
public_key,
verify=True,
algorithms=["RS256"],
audience=[client_id_app_1],
)
is there a better way to just send the access_token to azure for validation?
EDIT:
So I changed the code in this way: on APP_2:
server_client_id = server_app_config.CLIENT_ID
app = msal.ConfidentialClientApplication(client_id=client_id_app_2, client_credential=client_secret_app_2, authority=f"https://login.microsoftonline.com/{tenant_id_of_APP_1_and_APP_2}")
result = app.acquire_token_for_client(scopes=[f"{client_id_app_1}/.default"])
access_token = result["access_token"]
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/octet-stream',
}
response = requests.post(url, headers=payload)
on APP_1 I validate the token in this way:
token = request.headers.get("Authorization").removeprefix("Bearer ")
public_key = get_public_key(token)
decoded = jwt.decode(
token,
public_key,
verify=True,
algorithms=['RS256'],
audience=[client_id_app_1],
)
Is this how the workflow should be?