It seems like a simple process and already lots of libraries out there but for some reason I cannot make it work. I am very new to Azure and not a native English speaker so I might use some terminologies wrong, bear with me.
I am developing a tool with python3.10 for internal use and I need to authenticate users. Our Azure team has registered the web app (single tenant) for me and gave me the tenant id, client id and client secret. End user can use Microsoft provided library (ms-identity) and the sample code (ms-identity-python-webapp)to get the Access Code(password flow) and send it to my code. Let's skip why we are doing it this way and security concerns. My question is how can I validate the access token? Googling returns some solutions using jwt module or python module called azure-ad-verify-token but none of them work for me. I also, saw a step by step instruction on how find the public key from "login.microsoftonline.com/{tenant id}/discovery/v2.0/keys" and add Begin certificate/End certificate to access token but jwt.decode function always returns "Signature verification failed". Can someone help me understand what I am doing wrong?
jwt.decode(
access_token,
public_key, # public key found in discovery/v2.0/keys "-----BEGIN CERTIFICATE-----\nMII...
algorithms='RS256',
audience=client_id,)
You will face this issue if you are generating token for Microsoft Graph API:
In python:
And getting this error is normal behavior.
In Jwt.io website:
Even here we are getting Invalid Signature:
This can be resolved when you generate token for custom API in my case I exposed an API and added scope and followed SO-Thread:
Now added permissions like below:
And then grant permission:
Now used the python code taken from SO-Thread .
And then when I run the code I got output as expected:
"grant_type": "password",
"client_id": f"{client_id}",
"client_secret": f"{client_secret}",
"scope": "api://743-ac99-9e/custom_scope",
"username":"m9.onmicrosoft.com",
"password":"Welc3"
Now checked in jwt.io website:
Note:
The Graph API access tokens cannot be validated because they are not intended for the application. To check any permission for access token, you can use Expose API method to validate it.