I am creating a backend with Python and FastAPI to authenticate users using the OAuth flow. Unfortunately there are no implementations with FastAPI that I could find so I adapted this Flask implementation https://github.com/auth0-samples/auth0-python-web-app/tree/master/01-Login
Using OAuth from authlib.integrations.starlette_client I’m able to trigger the OAuth flow and a user can navigate to the single singon page and login. However, the access_token returned from the authentication flow is not working.
The token seems to be malformed with 2 dots ( … ) in what I think should be the payload (?) and when I try to verify this token with our other backend it returns an error with Audience Invalid.
This is the code I used:
oauth_client = OAuth()
oauth_client.register(
name=“auth0”,
client_id=settings.auth0_client_id,
client_secret=settings.auth0_client_secret,
audience=settings.auth0_audience,
authorize_url=f"https://{settings.auth0_domain}/authorize",
token_url=f"https://{settings.auth0_domain}/oauth/token",
server_metadata_url=f"https://{settings.auth0_domain}/.well-known/openid-configuration",
client_kwargs={
“scope”: “openid profile email”,
},
)
The audience parameter there doesn’t seem to do anything BTW
Then from a login route I direct the user to a callback:
@router.get(“/login”)
async def login(request: Request):
try:
return await oauth_client.auth0.authorize_redirect(
request=request,
redirect_uri=settings.auth0_callback_url,
state=request.query_params.get(“state”),
)
except Exception as e:
logger.error(
f"Could not redirect to Auth0 login page. Error: {str(e)}", exc_info=True
)
raise CouldNotRedirectToOAuthException(str(e))
@router.api_route(path=“/callback”, methods=[“GET”, “POST”])
async def callback(request: Request):
try:
code = request.query_params.get(“code”)
state = request.query_params.get(“state”)
if code:
# Exchange the authorization code for an access token using Auth0’s token endpoint
token = await oauth_client.auth0.authorize_access_token(request)
# the access_token returned by authorize_access_token is not well formed.
verified_token = await verify_token_authenticity(token)
return RedirectResponse(settings.slack_install_url)
except Exception as e:
logger.error(
f"Could not verify user authentication. Error: {str(e)}", exc_info=True
)
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=str(e))
I would appreciate any help in this topic