Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to store tokens/secrets with FastAPI?

Tags:

python

fastapi

I'm working with FastAPI and Python on the backend to make external calls to a public API. After authentication, the public API gives an access token that grants access to a specific user's data. Where would be the best place to store/save this access token? I want to easily access it for all my future API calls with the public API service. I don't want a DB or long term storage as it only needs to last the session for the user. Appreciate all help!

like image 799
oscar-lauth Avatar asked Nov 30 '25 02:11

oscar-lauth


1 Answers

Almost a year later, but I found a clean solution I was pleased with. I used Starlette's SessionMiddleware to store the access_token and user session data in the backend.

Example:

from fastapi import Request
...
@router.get("/callback")
async def callback(request: Request):
 ...
 request.session["access_token"] = access_token

Then later, in any endpoints where I need to use the token or get session data:

@router.get("/top_artists")
async def get_top_songs(request: Request):
 ...
 access_token = request.session.get("access_token")

This stores access_token and any other session data you want on the backend. Then, a cookie, 'session_id', is stored client-side and passed through Request to retrieve the session data from the server.

like image 189
oscar-lauth Avatar answered Dec 01 '25 18:12

oscar-lauth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!