How to generate a unique auth token in python? How to generate a unique auth token in python? flask flask

How to generate a unique auth token in python?


You can use like as mentioned the builtin uuid module. The new secrets module released in 3.6 is also capable of creating unique tokens also.

from uuid import uuid4rand_token = uuid4()

The function below creates a unique token every time it's called. The os.urandom method returns 20 random bytes as a string and the binascii.hexlify method converts each of those 20 bytes into 2-digit hex representation of that byte. This is why the return value is twice as long.

If you want to use this approach and need tokens to be specific length, use half of the length you need as an argument to the os.urandom method.

def generate_key(self):    return binascii.hexlify(os.urandom(20)).decode()


OK, this is old, but I'm chiming in anyway. You need to decide: Do you want unique or random? Choose one.

If you want unique, use UUID. The whole purpose of UUIDs is to make sure you generate something that's unique. UUID stands for Universally Unique ID.

If you want something that's random, use os.urandom. Truly random results cannot be limited to uniqueness constraints! That'd make them not random. Indeed, it'd make them UUIDs.

Now, for your question, you're asking for an auth token. That means you're using this for security purposes. UUIDs are the wrong solution and generating a secure number is the right one. Could you have a collision when generating a random number instead of a UUID? Yes. But it's unlikely unless you've got a gazillion users. You'll want to do your math on this, but my recommendation is: Don't use UUID when you mean to use random.

Oy.


Look at the uuid() library. Docs are here:

https://docs.python.org/2/library/uuid.html

and a previous discussion of the question is here:

How to create a GUID/UUID in Python

with lots of good details.