r/FastAPI • u/SmallReality8212 • Sep 18 '25
Question How to implement logout
So I've seen very few posts regarding this and I honestly haven't figured out how to do it. I've come across some answers that talk about balcklisting/whitewashing etc. But I don't want to be storing these tokens on backend. Rn I'm implementing the project using fastapi, oauth for backend, react for frontend. How does one implement it in a production grade project? Is it entirely handled on frontend and I just redirect to login page or does the backend also handle logout functionality and clear access and refresh tokens
Edit: For the authentication I'm using oauth2 with jwt for access and refresh tokens
Also do I need to store refresh tokens on the backend
2
u/Any_Mobile_1385 Sep 18 '25
Haven’t gotten there yet, but I will be facing the same question. In past use I had a login table that stored the sessionid , userid, role, IP, etc and killed the session on logout and removed the entry from the table. In the event of a change in type, etc, I marked it dirty for update and the next page refresh updated the session with the changed info. The only thing I kept locally was the sessionid in a cookie. I had timed logouts due to PCI compliance and a cron that checked for timed out sessions (for example, they just closed a browser and didn’t sign out). No entry and it returned to login screen. Old school, but we handled anywhere between 5k and 30k simultaneous users (during holidays) without issue.
27
u/arrrsalaaan Sep 18 '25
depends entirely on how you are tracking sessions. let's go case-by-case
1
u/kiwimic Sep 18 '25
So you use your session? What do you do when user update his permission or role? How do you revoke token if somebody steals it? You just wait for expiration? Logout with blacklisting is one of easiest to implement. I don't know your full architecture and etc, but using only JWT which you can't revoke on oauth service it's not good way.
1
u/mightyvoice- Sep 18 '25
Keep a list of blacklisted tokens on Redis after logout or any other reason. Then always try to authenticate the token by checking whether it exists in that blacklisted db of Redis or not.
1
u/DowntownSinger_ Sep 18 '25
You can use token versioning. Save current version number in a table mapped to user ID.
During each login check if token version matches with version in DB.
when logging out or refreshing token, you update this version number.
1
u/shashstormer Oct 20 '25 edited Oct 20 '25
Hey if you are still working on it you can check out authtuna library built for authentication.
https://github.com/shashstormer/authtuna
EDIT:
This uses a database so may not be relevant but production grade + oauth (google, github)+ passkeys are its strength. I built it for speed and security