Skip to content Skip to sidebar Skip to footer

How To Generate A Unique Auth Token In Python?

I am trying to write a token based auth in flask for my android app. For that I need a unique token using which I can verify the user. Itsdangerous library provide a JSONWebSignat

Solution 1:

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 importuuid4rand_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.

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

Solution 2:

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.

Solution 3:

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.

Solution 4:

I wrote a little helper function for generating a unique token in django models. You can call it from the save() method of your model. It generates a candidate token using a defined function, searches the existing rows in the database for that candidate token. If it finds one, it trys again, otherwise, it returns the candidate string. Note that there is a small race condition in this, but is unlikely to occur with a token function with a sufficiently large range of outputs.

defgenerate_unique_token(Model,
                      token_field="token",
                      token_function=lambda: uuid.uuid4().hex[:8]):
"""
Generates random tokens until a unique one is found
:param Model: a Model class that should be searched
:param token_field: a string with the name of the token field to search in the model_class
:param token_function: a callable that returns a candidate value
:return: the unique candidate token
"""
unique_token_found = Falsewhilenot unique_token_found:
    token = token_function()
    # This weird looking construction is a way to pass a value to a field with a dynamic nameif Model.objects.filter(**{token_field:token}).count() is0:
        unique_token_found = Truereturn token

Then, you can find a unique token simply by calling

token = generate_unique_token(MyModelInstance, "token_field_name")

It even supports using other methods of generating tokens. For example, if you want to use the full uuid, you can simply call it like this:

token = generate_unique_token(MyModel, "token_field_name", lambda: uuid.uuid4().hex)

Solution 5:

A possible solution is to AES encrypt the time when the token expires + the username which makes it fairly easy to spot expired tokens and requires no extra database space for the tokens

Post a Comment for "How To Generate A Unique Auth Token In Python?"