-
Notifications
You must be signed in to change notification settings - Fork 68
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
Calling your APIs from Python not working #156
Comments
Please provide full code snippets and error messages. |
I'm really confused here - something worked on Wednesday no longer works today? Can you please give me some errors or context here? I haven't changed anything in this library for a while. |
this error pops up (while running uvicorn) as soon as I add this section to the code: when I take that section of code out, I am able to enter my authorization credentials, but when I submit them I'm met with this page: It's not adding the app information, it's trying to load "https://login.microsoftonline.com//oauth2/v2.0/authorize?" |
Well I'm a fool. I misnamed my .env file. it was just env. and since I saw an issue left on the repo 3 hours before I ran into the problem, I just assumed my code was right and something changed in the repo. After renaming the file, everything worked correctly. |
Glad you solved it. Thanks for the kind words 😊 |
I am using B2C tenant. I can authenticate FastAPI using Azure AD B2C. I want to expose my FastAPI from other Python. Hence I followed following URL : I created client secret in fastapi-az-b2c-api-OpenAPI application. Please find by code below
Now I am getting following error : Please let me know, if I am missing anything. |
Hmm.. @davidhuser , do you know if there's something specific for B2C? 🤔 |
I don't use it myself yet but thought it might be good to do a little digging. According to import json
from typing import Union
from httpx import AsyncClient
import asyncio
# change to your own method:
settings = get_settings()
CLIENT_SECRET = 'xxx' # the secret you created
API_URL = 'https://path-to-my-app/api' # the URL of the FastAPI
ENDPOINT = 'myEndpoint' # the endpoint you want to call
async def get_token(client: AsyncClient) -> Union[str, None]:
url = f"https://{settings.TENANT_NAME}.b2clogin.com/{settings.TENANT_NAME}.onmicrosoft.com/{settings.AUTH_POLICY_NAME}/oauth2/v2.0/token"
headers = {"Content-Type": "application/x-www-form-urlencoded"}
data = {
"client_id": settings.APP_CLIENT_ID,
"scope": f'https://{settings.TENANT_NAME}.onmicrosoft.com/{settings.APP_CLIENT_ID}/.default',
"client_secret": CLIENT_SECRET,
"grant_type": "client_credentials",
}
r = await client.post(url, headers=headers, data=data)
if r.status_code == 200:
token = json.loads(r.text)["access_token"]
return token
else:
print(f"Failed to get token, status code: {r.status_code}, message: {r.text}")
return None
async def call_api(client: AsyncClient, token: str):
r = await client.get(f"{API_URL}/{ENDPOINT}", headers={"Authorization": f"Bearer {token}"})
if r.status_code == 200:
print(r.text)
else:
print(f"Failed to call API, status code: {r.status_code}, message: {r.text}")
async def main():
async with AsyncClient() as client:
token = await get_token(client)
if token:
print("Token:", token)
await call_api(client, token)
asyncio.run(main()) Let us know if it works. |
Note that this is still valid
|
I am now getting following error : Failed to call API, status code: 401, message: {"detail":"Token contains invalid claims"} |
Looks like you got a token but the library raised an https://github.com/Intility/fastapi-azure-auth/blob/main/fastapi_azure_auth/auth.py#L213 any more info in your FastApi app logs? |
Also please decode the token at jwt.io and show the decoded version to us (You can redact the names etc of course) Also, for the future, please add as much information to every post/question you can. Eventually those who help you stop asking questions, which ends up in you not getting help. Enable debug logs, show entire stack traces, explain your entire environment. Makes this so much easier for all of us 😊 |
@davidhuser and @davidhuser. |
the root cause is not yet clear to me because we don't have the info of the error. Can you check if you can log Here's a starting point for debugging. import logging
from fastapi import FastAPI
# Configure root logger
logging.basicConfig(level=logging.DEBUG)
# Set logging level for library
logging.getLogger('fastapi_azure_auth').setLevel(logging.DEBUG)
# Ensure logs are propagated
logging.getLogger('fastapi_azure_auth').propagate = True
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"} edit: changed to |
We should probably add a troubleshooting section (like I have for my Django package)in the docs and make an issue template. Thanks for all your contributions, help and reviews @davidhuser.😊 |
@davidhuser : Please find below debug log: I agree, troubleshooting section will be very helpful. Specially, Azure AD B2C. Thanks @davidhuser and @JonasKs for help. |
thanks for showing us the debug logs. as per logs, |
Agree. We can also add a leeway-setting, it's been hard coded to 0 atm. Someone had a similar issue last month. |
I did following changes:
It worked. @davidhuser & @JonasKs : Thank you very much for support. |
Glad you solved it. I've added a new issue for allowing the settings to be set. PRs welcome. |
ah got it, great that it works now. I see the docs use OPENAPI_CLIENT_ID as the secret was created for that app reg. Will add two doc PRs for "Calling the APIs with Python" and a "troubleshooting" page. |
Hi,
I followed all step present in following URL :
https://intility.github.io/fastapi-azure-auth/usage-and-faq/calling_your_apis_from_python
However, I am getting "AADSTS500011: The resource principal named api:// was not found in the tenant named XX. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant."
If I change following statement :
'scope': f"https://{settings['TENANT_NAME']}.onmicrosoft.com/{settings['APP_CLIENT_ID']}/.default"
then I get token in azure_response.
however while calling FastAPI, I get "Unable to verify token. No signing keys found".
Please guide me.
The text was updated successfully, but these errors were encountered: