如何在python中生成唯一的身份验证令牌? [英] How to generate a unique auth token in python?

查看:192
本文介绍了如何在python中生成唯一的身份验证令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在烧瓶中为我的Android应用程序编写基于令牌的身份验证。为此,我需要一个唯一的令牌,通过它可以验证用户。

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库提供了JSONWebSignatureSerializer函数,可以使用该函数创建JWT令牌。因此,我的第一个问题是,将JWT用于基于移动的身份验证是否安全?

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 ?

其次,我对django rest框架如何生成其令牌进行了一些研究。 / p>

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?

为python中的移动应用生成唯一令牌的基本方法是什么?

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

推荐答案

您可以像提到的那样使用内置的 uuid 模块。 3.6中发布的新的 secrets 模块还能够创建唯一的令牌。

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每次调用时,下面的函数都会创建一个唯一的令牌。 os.urandom 方法返回20个随机字节作为字符串,而 binascii.hexlify 方法转换这20个字节中的每一个转换为该字节的2位十六进制表示形式。这就是为什么返回值是两倍长的原因。

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.

如果您想使用此方法并且需要令牌具有特定的长度,请使用一半 os.urandom 方法的参数长度。

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()

这篇关于如何在python中生成唯一的身份验证令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆