-
Notifications
You must be signed in to change notification settings - Fork 202
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
example for web api token validation #147
Comments
Hi Cameron, thank you for your valuable question! You clearly did your research. :-) So, what you want is the token validation. And that is NOT the same as "client credentials flow". For what it's worth, client credentials flow is still about the token acquisition, not token validation. Regardless, we do not currently have a sample for token validation. I'm marking this as an enhancement item here, and we will take this into consideration when next time we update our plan. |
They you Ray. Yes, token validation is what I'm looking for. |
+1 for token example |
any example also would do. Thanks. |
Hi All The token I was able to get through following this link and restructed my app like the secureFlaskApp. Thanks for the help. |
A sufficient number of JWT validation checks is being performed in the Also,
update: This method may fail for access tokens, because they might be issued for another audience (e.g. Microsoft Graph API) and signed with audience-specific key. |
Hi @eprigorodov , thank you for the code review on our existing implementation. We love this community voices. :-) With regard to the topic you brought up above, it is actually a different topic than the current issue. The current issue is about Access Token validation, the topic you brought up is about ID Token validation. MSAL already performs ID token validation, we just validate it in a different-than-pyjwt way, but still specs-compliant. Should you have follow-up question on ID token validation, please create ANOTHER issue for its subsequent discussion. |
Would be great to have functionality to verify |
@rayluo, thank you for pointing out, indeed I was looking for an issue about ID token validation and misread the actual subject. @cheslijones, access tokens issued for Microsoft APIs are usually supposed to be opaque for the client and will be validated by the very endpoint service. Clients just send them as-is to the target API and process responses with possible validation errors. |
@eprigorodov It sounds like the library does not support my use case. |
@cheslijones The MSAL is a client authentication library. Server middleware libraries are listed here: https://docs.microsoft.com/en-us/azure/active-directory/develop/reference-v2-libraries#microsoft-supported-server-middleware-libraries For Django you can try authlib. It uses the same approach as the code in the comment above. JWT signature verification will work if access token is signed with one of "generic" Microsoft keys, the ones exposed via well-known OpenID configuration. For that authorization request, token request and access token should include one of scopes defined for the web application itself (listed under "Scopes defined by this API" on the blade "Expose an API" of the Azure App Registration). |
No caso procuro a mesma solução em relação a validação do token. Pois no caso quem vai conectar com o usuário é o front-end (web) e manter o usuário conectado para cada solicitação que ele fizer na api do back-end, mas ao passar para o back-end a requisição, é necessário que ele valide o token para saber se é daquele AD especifico usando o APPID e TENANTID, caso contrário essa conexão com o AD teria que ser feito pelo back-end, que não faz nenhum sentido, quando a idéia é fazer login usando credencias microsoft e manter o usuário conectado pelo tempo de expiração do access token. |
Of course, there are reference solutions out there as mentioned above. And yes, this is a client authentication library, but the recommended most secure flow is the authorization code flow, which requires this to be run on the server in order to have control of how you issue tokens to the clients (client secrets). I think this makes it a very suitable place to include a I think including this feature in the library would be great for us users and will mitigate potential vulnerabilities of improper validation by everyone re-implementing reference solutions and making mistakes. |
Hello guys, I have the same problem, @rayluo any evolution at that point? |
Sorry, not yet. :-( |
hello guys, I too have same problem, @rayluo any evolution? |
hey, I found a good example for the token validation that also uses the would be awesome if |
Hi I am using your code to decode client side token given by teams to tab. I have also raised my query here : https://stackoverflow.com/questions/67401139/using-python-decode-client-side-token-fetched-by-microsoft-teams-and-given-to-ta I am getting this error Is there anything that you can help me with? I used Application Id(when we register app in azure active directory) as client_id. |
Hi, I decoded the token again in jwt.ms and find the |
Hi @datasleek, as per documentation, the audience "aud" claim in ID token is either Application (client) ID or Application ID URI, e.g.:
Application ID URI can also be set in the Azure Portal interface, on the "Expose an API" blade of Application Registration object. The rules for audience claims in access tokens are more complex, they depend on requested scopes. For example, tokens issued for Microsoft Graph scopes may conatin a magical audience OID "00000003-0000-0000-c000-000000000000". It is possible also to turn off audience verification in |
Hi @eprigorodov , I apologise for late reply. Your code helped me to successfully decode the clientSideToken fetched by microsoft teams from AAD . Regarding |
Hi @eprigorodev |
For anyone else searching for this, I have found this example: https://github.com/ivangeorgiev/gems/tree/main/src/python-azure-ad-token-validate which validates access token. |
@rayluo, is there currently a plan to add token validation to this library? I understand it's not necessary to validate tokens for the graph API. However, I'm currently using this library to obtain tokens for my own API, by setting the scopes to point to my app registration id. The access token that my client app obtains is subsequently sent along with requests to the API, so I need to validate it in that API. I'm working with both Azure AD and B2C because my organization supports different login methods, and I found out those tokens need to be validated differently (the JWKS are different). I implemented my own code to validate the tokens, but it was quite difficult to figure out how to do that, and the MS documentation wasn't helpful in that regard. It would be great if this library could be used server-side to handle signature validation. Is there any way I can contribute to such a feature? I think the previously mentioned examples are helpful for AD validation. For B2C, I found this article helpful: https://robertoprevato.github.io/Validating-JWT-Bearer-tokens-from-Azure-AD-in-Python/. For anyone using Fast API, I recommend this library: https://github.com/Intility/fastapi-azure-auth |
Feel free to share a link to your implementation, so that we (Microsoft and the entire community) can utilize it. We have not decided whether token validation feature should be part of this MSAL library, but it doesn't harm to consolidate some working code as a sample. In fact, some other Microsoft libraries/components were initially started as a sample, and evolve from there. |
This repo from MS may be useful for someone reading this in search of a FastAPI plugin or a generic reference solution to validate access tokens. It includes a decorator function (one liner above the method serving an api endpoint) for FastAPI, but the source code is similar to other references like mentioned above. A few thoughts on that reference:
@rayluo How would you recommend approaching this now for access token validation in a custom api? Using something from msal-python, a reference implementation, or authlib/pyjwt etc ? |
This drives me crazy, any helps appreciated.
T1St-dLTvyWRgxB_676u8krXS-I from kid field of below They are totally different in length, none of them match.
|
@cutesweetpudding - the jwks_uri is found by going to the well-known metadata endpoint of the identity provider. This is typically the authority + ".well-known/openid-configuration". For example https://login.microsoftonline.com/common/.well-known/openid-configuration |
Thanks for replying, the issue I have is I can't find the signing key for my access token. I think my issues are more likely associated with multi tenants and user flow, I read documents it says I can't use common signing keys, I have to specify a custom signing key? I didn't do it obviously. So where can I find the signning key or how I can configure a custom signning key. |
@cutesweetpudding, what is the token scope? |
@eprigorodov - afaik all Bearer tokens are signed by the token issuer (Identity Provider). The Identity Provider's public key is publicly available. Maybe the scenario you are thinking of is JWEs (encrypted JWT)- in this case the JWT payload is encrypted with a key that only the resource and the Identity Provider share. This prevents clients from decoding the token and accessing private information from the claims. @cutesweetpudding - I believe the Identity Provider is B2C, because only B2C has the concept of "policies". There aren't multiple tenants in B2C and "common" isn't a thing. Here are the details from one of our integration tests: Authority: The OIDC document is at: and the jwks document is at: PS: The "common" tenant is a concept that is specific to AAD / for "Work and School" accounts. A user can be a guest in another tenant and "common" means "let AAD figure out the user's home tenant". |
Here's my simplistic code that shows how to validate the signature of the token above. Note that this is not production ready code and more checks probably need to happen for an app to trust this token. This is just to show the where to get the public key for a B2C authority. import json
from urllib.request import urlopen
import jwt
token = "TOKEN_GOES_HERE"
key_url = "https://msidlabb2c.b2clogin.com/msidlabb2c.onmicrosoft.com/b2c_1_ropc_auth/discovery/keys"
jwks_client = jwt.PyJWKClient(key_url)
signing_key = jwks_client.get_signing_key_from_jwt(token)
payload = jwt.decode(
token,
signing_key.key,
algorithms=["RS256"],
audience="2ae335cd-5ec9-4eee-8148-58be9e8020c9", # This is your web api's Application ID (you get it from Azure portal)
)
print(payload)
|
Hi everyone, I am having a similar issue. I need to validate incoming JWT which is acquired using |
I need to validate the identity using a Flask web API. It is a different flow than the ms-identity-python-webapp example. I think I just need to validate the jwt token and some of its values similar to what is done here with this code. Is this something that can be done with msal or am I better off using code like that?
Client credentials flow
The text was updated successfully, but these errors were encountered: