I generate oauth2 access and refresh tokens and store them in my database. I generate these tokens using UUID v4 and remove the dashes. I used to delete the tokens after they expire but now I store all of them because I thought of something that could happen.

What if an attacker stored locally all of the access tokens that were generated for him and he kept using these access tokens again and again for authorization. Since I, as the DB admin, was deleting the generated tokens, the DB has no way of knowing that the token is unique. Therefore if the UUIDv4 algorithm generates an access token for a different user and it's a collision (same UUID as one generated previously) and the attacker found that collision, he could get into the service since he has the tokens that have been generated before.

My question is should I worry about this and keep all my tokens in case of collision to check for uniqueness or should I delete the access and refresh tokens after they expire and trust that UUIDv4 has enough entropy to prevent this?

I'm also worried that if I keep all the tokens, it's going to inflate the database since the access tokens expire every hour and are regenerated the next time the user takes an action.

Any help is appreciated!


If you are generating version 4 UUIDs using a cryptographically secure RNG, the probability of a previously issued token matching a currently valid token is exactly the same as the probability of any random token created by the attacker matching a current token.

This means that an attacker with previous tokens has no advantage over any other attacker, and you do not need to keep expired tokens in the database.

Focus instead on ensuring you're using a really secure RNG, preferably sourced from a physical source of randomness.

A more useful reason to keep expired UUIDs is to detect problems with the RNG. If you ever get a repeated UUID, it is possible that there is a bug in your random number generation, similar to the Debian OpenSSL bug (DSA-1571-1).

  • I have a feeling that storing every access token to detect if there's a repeated UUID would take a tremendous amount of storage space. Since the tokens are generated on the hour (based on usage). Let's say best case scenario at some point we have 100k daily active users. Storing the tokens is around 300Bytes (with other metadata). If we generate tokens 30% of the day every hour (around 7 tokens), then we are storing an extra 6GB/month. It might not be worth it later on but you're right, in the beginning it might help detect problems with our RNG... – programmerdave May 15 '14 at 19:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.