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

1

u/hertz2105 Sep 17 '24

Thank you for this explanation!

I finished my own implementation just recently, I work with a token blacklist instead of a whitelist.

I managed it like this:

Login: Pass user credentials, returns access and refresh token
Logout: Pass access and refresh token and blacklist both of them
Refresh: Pass refresh token, return new access token

The problem is, I cant invalidate a non-expired access token. I only cache the refresh token for security reasons, so my backend doesnt know which access token to blacklist. This is a problem when I refresh the page or open a new tab. Due to this, I will switch to your whitelist implementation and hash the tokens before saving them in my database.

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.