Rails, ruby: does SecureRandom.urlsafe_base64 need to be checked for uniqueness for tokens? Rails, ruby: does SecureRandom.urlsafe_base64 need to be checked for uniqueness for tokens? ruby ruby

Rails, ruby: does SecureRandom.urlsafe_base64 need to be checked for uniqueness for tokens?


SecureRandom.uuid generates uuids. A UUID is 128 bits long, and can guarantee uniqueness across space and time. They are designed to be globally unique, unlike urlsafe_base64. See RFC4122.


It doesn't ensure uniqueness but, as svoop said, it's extremely unlikely that you'll get the same result twice.

My advice is: if all you need are random, unique and unguessable tokens, and you don't have hundreds of thousands of users, then use it without worrying.

If you absolutely want unique tokens (e.g. there is some legal requirement), then combine a unique field associated with the user (e.g. the user email) and a random salt, and hash the result.

A naive implementation would be:

require 'securerandom'require 'digest/md5'def generate_user_token(user)  digest(user.email + random_salt)enddef random_salt  SecureRandom.urlsafe_base64enddef digest(string)  Digest::MD5.hexdigest stringend


No, you won't see a duplicate in your lifespan.

32 is the length (in bytes) of the random number generated before it get's converted to an urlsafe base64 string, so chances of a duplicate are roughly 1 to 10'000'000'000'000'000'000'000'000'000'000. That's 10e31 and the universe is only 43e17 seconds old.