# Triggering an OAuth flow from a Python FastAPI backend, returns an access\_token malformed

**URL:** <https://community.auth0.com/t/triggering-an-oauth-flow-from-a-python-fastapi-backend-returns-an-access-token-malformed/119028>\
**Category:** Get Help\
**Tags:** configuration, application\
**Created:** [October 20, 2023, 3:33pm UTC](https://community.auth0.com/t/triggering-an-oauth-flow-from-a-python-fastapi-backend-returns-an-access-token-malformed/119028 "2023-10-20T15:33:24Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![leonardo1](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/leonardo1/32/48843_2.png) [@leonardo1](https://community.auth0.com/u/leonardo1)\
**Post date:** [October 20, 2023, 3:33pm UTC](https://community.auth0.com/t/triggering-an-oauth-flow-from-a-python-fastapi-backend-returns-an-access-token-malformed/119028/1 "2023-10-20T15:33:24Z")

</div>

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](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

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [October 20, 2023, 7:07pm UTC](https://community.auth0.com/t/triggering-an-oauth-flow-from-a-python-fastapi-backend-returns-an-access-token-malformed/119028/3 "2023-10-20T19:07:28Z")

</div>

Hey @leonardo1 welcome to the community!

> [@leonardo1](#):
>
> 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.

What does the the token payload look like when you paste it into [jwt.io](http://jwt.io) (please redact any sensitive info)? Additionally, what does the payload look like for the authorize request when inspecting the network tab? Again, please redact any info you deem necessary.

 ![Screenshot 2023-10-20 at 12.06.11 PM](https://global.discourse-cdn.com/auth0/original/3X/f/6/f6f2321681c59c606e3c4e83db687e8804273fbd.jpeg)

---

<div class="post-metadata">

**Author:** ![leonardo1](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/leonardo1/32/48843_2.png) [@leonardo1](https://community.auth0.com/u/leonardo1)\
**Post date:** [October 20, 2023, 7:57pm UTC](https://community.auth0.com/t/triggering-an-oauth-flow-from-a-python-fastapi-backend-returns-an-access-token-malformed/119028/4 "2023-10-20T19:57:14Z")

</div>

Hey @ty.frith, thank you!

This is what I see in [jwt.io](http://jwt.io)

 ![Screenshot 2023-10-20 at 2.32.31 PM](https://global.discourse-cdn.com/auth0/original/3X/c/4/c4116830f36988e72a5cae5a39d7eb1552d2e108.png)

this is what is see for the payload:

 ![Screenshot 2023-10-20 at 2.54.01 PM](https://global.discourse-cdn.com/auth0/original/3X/9/9/997bbf445f7c9f79303fbd0e50c6ab91ace371a0.png)

I do see the payload is missing a lot of parameters compared to the one you have shared.

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [October 20, 2023, 9:20pm UTC](https://community.auth0.com/t/triggering-an-oauth-flow-from-a-python-fastapi-backend-returns-an-access-token-malformed/119028/5 "2023-10-20T21:20:29Z")

</div>

Thanks for sharing!

The access token does indeed seem to be missing some parameters - `audience` being critical to receiving a jwt as opposed to an [opaque token](https://auth0.com/docs/secure/tokens/access-tokens#opaque-access-tokens). There’s definitely an issue with the way the authorize request is being configured/constructed.

If you want to quickly test your API, you can always navigate to the API in your dashboard → Test tab and grab an access token for an authorized client.

 ![Screenshot 2023-10-20 at 2.20.14 PM](https://global.discourse-cdn.com/auth0/original/3X/3/c/3c3e4d83e7ae2efe6355cedcffad3b5abe489a14.jpeg)

---

<div class="post-metadata">

**Author:** ![leonardo1](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/leonardo1/32/48843_2.png) [@leonardo1](https://community.auth0.com/u/leonardo1)\
**Post date:** [October 20, 2023, 10:53pm UTC](https://community.auth0.com/t/triggering-an-oauth-flow-from-a-python-fastapi-backend-returns-an-access-token-malformed/119028/6 "2023-10-20T22:53:37Z")

</div>

Well, that is a great question @ty.frith

This is my first time using Auth0 to authenticate users. I have inherited the stack and I don’t understand the configuration.

This are our Applications:

 ![Staging](https://global.discourse-cdn.com/auth0/original/3X/d/8/d8416f92d203f70f1fd13f63c59e90c919d0bc4f.png)

 ![API Staging](https://global.discourse-cdn.com/auth0/original/3X/f/c/fcf27cf973f00c17263d413cd6aaa66e846eaef2.png)

This is our API:

 ![API](https://global.discourse-cdn.com/auth0/original/3X/d/6/d65372925f617b144c37c99612d4a96abf765e66.png)

 ![API Staging Connection](https://global.discourse-cdn.com/auth0/original/3X/b/d/bd1ea5789c27f77e4e046e8f76778eac16ed2ec6.png)

Our React (Frontend APP) uses the Staging oauth app client\_id and client\_secret to do loginWithRedirect to the users and after that it does getAccessTokenSilently.

I wanted to replicate process from the React App and direct users to login and get the token from that Stating application’s client\_id and client\_secret.

When I test the token from the API that token works but it has no user attached, which is probably fine.

What I don’t understand is why we have 2 different apps with different credentials to manage SSO and API tokens.

Do you have any documentation of how to achieve this process in python correctly?

---

<div class="post-metadata">

**Author:** ![ty.frith](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/ty.frith/32/58484_2.png) [@ty.frith](https://community.auth0.com/u/ty.frith)\
**Post date:** [October 24, 2023, 12:35am UTC](https://community.auth0.com/t/triggering-an-oauth-flow-from-a-python-fastapi-backend-returns-an-access-token-malformed/119028/7 "2023-10-24T00:35:43Z")

</div>

> [@leonardo1](#):
>
> When I test the token from the API that token works but it has no user attached, which is probably fine.

That’s good news at least!

> [@leonardo1](#):
>
> What I don’t understand is why we have 2 different apps with different credentials to manage SSO and API tokens.
> 
> Do you have any documentation of how to achieve this process in python correctly?

In this case you can ignore the M2M app and focus on the SPA as you will use this to get a user’s access token. We unfortunately don’t have a clear example, but here is what I would do:

- Here is our [Python sample](https://github.com/auth0-samples/auth0-python-api-samples/tree/master/00-Starter-Seed) which utilizes Flask. You should be able to get this up and running with your domain and API identifier fairly quickly.

- Take a look at our [React sample app](https://github.com/auth0-samples/auth0-react-samples) and get it up and running with your SPA application ids. Be sure and add the `audience` (your API identifier) in the [auth\_config.json](https://github.com/auth0-samples/auth0-react-samples/tree/master/Sample-01#configure-credentials) file. When running the app and logging in, have the network tab open so that you can extract the user’s access token - You will see a call to the `/token` endpoint:  

- Once you have the access token from a test user, check out our docs on [how to use the API](https://auth0.com/docs/quickstart/backend/python/02-using). This is the quickstart that pairs with our Python sample API/app referenced in bullet 1. This outlines a few curl requests you can make to the Python sample API you have running using the access token you extracted previously.

Hope this helps!

---

<div class="post-metadata">

**Author:** ![leonardo1](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/leonardo1/32/48843_2.png) [@leonardo1](https://community.auth0.com/u/leonardo1)\
**Post date:** [October 24, 2023, 2:58pm UTC](https://community.auth0.com/t/triggering-an-oauth-flow-from-a-python-fastapi-backend-returns-an-access-token-malformed/119028/8 "2023-10-24T14:58:07Z")

</div>

@ty.frith I have tried what you sent me, and the React code works fine and gives me the token as you mentioned and I can use it in my Backend to authenticate.

One thing I noticed I was missing was to redirect the users after doing SSO to the homepage of my application. After doing that I can see the call that looks like this:

https://\*\*\*\*\*\*.us.auth0.com/u/login?state=hKFo2SB5QXM0eUc2QjBrcFpZbVhsOFdnZ3VHZk14c2dzdGdEMqFur3VuaXZlcnNhbC1sb2dpbqN0aWTZIE5tRWw1dzhQM041bkQwcWFGcGNlenRtWXN1N2kzajZzo2NpZNkgOEdqUlBHMzNZb0hpQjc0SFNWV0xDOHdLRmt4Yk40dXk

with the payload of the username and password in it.

Now I think the problem here is that I’m using FastAPI to return HTML templates and I don’t have a way to get the bearer token as you mention above in that token call – I guess that is probably getTokenSilently --.

This:

 ![token](https://global.discourse-cdn.com/auth0/original/3X/5/0/5004470fd0769f8e1d841f22668af0099bb95e8b.png)

How can I do that call from the Python Backend? Because I don’t have the username and password of the user to make that call from the backend. I probably need some other way of getting that token on behalf of the user.

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/auth0/original/3X/b/5/b560f266932fcce5d57f09a6595bd50518cae3f3.jpeg) [@system](https://community.auth0.com/u/system)\
**Post date:** [November 18, 2024, 10:51pm UTC](https://community.auth0.com/t/triggering-an-oauth-flow-from-a-python-fastapi-backend-returns-an-access-token-malformed/119028/9 "2024-11-18T22:51:35Z")

</div>

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
