Chapter 18: Tokens are never deleted

I was implementing token authentication as per chapter 18 of the book. But then I realized. The tokens get saved every time a user logs in, but are never deleted, or never expire. Wouldn’t loggin in again and again cause more tokens per user to pile up in the database? What would be a nice implementation of expiring tokens? Or deleting them even?

Cheers Jaap

@0xtim Can you please help with this when you get a chance? Thank you - much appreciated! :]

Hi @bababoega - you’re right, currently the token implementation is very basic.

For expiring tokens you can add an expiry date to the token model and use custom middleware to check if the token is valid.

To delete them, you can either delete expired tokens when you check them and find out they’re expired or use a background task to scan for expired tokens and delete them

1 Like

Thanks @0xtim, not wanting to rewrite TokenAuthenticationMiddleware how would I let those play together nicely? I would just like to add an additional check that check expiration of the token in the database.

You can add a new middleware to run after TokenAuthMiddleware that checks the expiry date using the authenticated token. IIRC the token should be saved in the auth cache so there shouldn’t be another database lookup.

This my solution…
image

@choioi Thank you for sharing your solution - much appreciated!