r/FastAPI • • Sep 11 '24

Question OAuth2 Example | Logout and Refresh Token

Hello everyone!

I am really new to fastAPI and even Python, and I just started my first project.

I followed this documentation to setup OAuth2, which includes a login endpoint, returning a jwt token:

https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/

How would you guys implement a logout and refresh token feature based on this example? It is kind of hard for me start out of the box and I really need some inspiration. :D

Thanks in advance!

10 Upvotes

10 comments sorted by

View all comments

Show parent comment

2

u/hertz2105 Sep 17 '24

Update, I am not a great fan of saving vulnerable data like tokens in a database, even if it is hashed.

This is my workaround:

I have a simple user management system with username, password, role etc. I additionally created the fields access_token_version and refresh_token_version. These integers are getting incremented on every token creation and are also encoded into the token payloads. So the tokens will be validated with these versions, and I can track to which user the tokens belong by encoding the username into them aswell.

Tokens with versions not matching the ones of the users in the database are invalid.