Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 JSONWebSignatureSerializer function using which I can create JWT token. So my first question is, is it safe to use JWT for mobile based auth ?

Secondly, I did a little bit research on how django rest framework generates its token.

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

Is this token unique or just a random one? Which one should I use for a mobile based auth?

What is the based way to generate a unique token for mobile application in python ?

like image 688
saprative Avatar asked Dec 28 '16 01:12

saprative


People also ask

How do you get unique tokens 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. The function below creates a unique token every time it's called.


1 Answers

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 uuid4

rand_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()
like image 69
Sean Parsons Avatar answered Sep 21 '22 09:09

Sean Parsons