最新消息:20190717 VPS服务器:Vultr新加坡,WordPress主题:大前端D8,统一介绍入口:关于

【已解决】Flask中如何设计和生成用户访问控制的access token

Flask crifan 910浏览 0评论

flask access token

flask how to generate access token

python – How do you implement token authentication in Flask? – Stack Overflow

flask restful api  access token

python – Flask-restful API Authorization. Access current_identity inside decorator – Stack Overflow

flask 生成access token

使用python实现后台系统的JWT认证 – 简书

使用 Flask 和 rauth 进行 Github Oauth 登陆 – Python – 伯乐在线

flask itsdangerous access token

Understanding Flask-Login Tokens Tutorial – The Circuit Nerd Blog

itsdangerous — itsdangerous

去试试:

<code>&gt;&gt;&gt; from itsdangerous import Signer


&gt;&gt;&gt; s = Signer('secret-key')


&gt;&gt;&gt; s.sign('my string')


'my string.wh6tMHxLgJqB6oY1uT73iMlyrOA'
</code>

经过尝试:

(RunningFast) ➜  staging python
Python 2.7.12 (default, Aug 23 2016, 10:06:20) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> from itsdangerous import Signer
>>> s = Signer(‘secret-key’)^[[D^[[D^H^H^H^H^H
  File “<stdin>”, line 1
    s = Signer(‘secret-key’)
                            ^
SyntaxError: invalid syntax
>>> s = Signer(‘\t\x9cw\x85&8\x99\x92\x81\xaa\xea\x9e\r\xd6H\xa26.\xf0\xa4\xb2\x92\xf0\xa6’)
>>> s.sign(*)^H^H
  File “<stdin>”, line 1
    s.sign(*)
            ^
SyntaxError: invalid syntax
>>> s.sign()
Traceback (most recent call last):
  File “<stdin>”, line 1, in <module>
TypeError: sign() takes exactly 2 arguments (1 given)
>>> s.sign(“”)
‘.bY5L7eRhOOOTlI1MkYX-pCk8YQI’
>>> s.gign^H
  File “<stdin>”, line 1
    s.gign
          ^
SyntaxError: invalid syntax
>>> s.sign(“”)
‘.bY5L7eRhOOOTlI1MkYX-pCk8YQI’
>>> from itsdangerous import TimestampSigner
>>> s = TimestampSigner(‘\t\x9cw\x85&8\x99\x92\x81\xaa\xea\x9e\r\xd6H\xa26.\xf0\xa4\xb2\x92\xf0\xa6’)
>>> s.sign(“”)
‘.Ct401Q.uZT7jWrX9rrpOy2LT6Kp8Jg1WuI’
>>> s.sign(“”)
‘.Ct402Q.5uY3ZKWFvMZvjsZ1_Lg4CxEbhMo’
>>> s.sign(“”)
‘.Ct405Q.tEQ2Wqh7QGz6hGuTNOm8VnH0tK8’
>>> s,s
(<itsdangerous.TimestampSigner object at 0x7f9ddd71ea10>, <itsdangerous.TimestampSigner object at 0x7f9ddd71ea10>)
>>> s.s.gin
Traceback (most recent call last):
  File “<stdin>”, line 1, in <module>
AttributeError: ‘TimestampSigner’ object has no attribute ‘s’
>>> s.sign(“user”)
‘user.Ct41HQ.6zjeVUjHbBrRdiWVouFFSAVzD6g’
>>> s.sign(“user”)
‘user.Ct41JA.A7UTfp0rbFlb6_hXlA6Xpx2kofI’
>>>

发现:

对于基本的Signer:每次都是一样的-》所以放弃。

对于TimestampSigner:每次都不同,所以采用。

此处,通过代码:

timestampSigner = TimestampSigner(app.secret_key)
from runningfast import timestampSigner
#def genAccesstoken(userId):
def genAccesstoken():
    #accesstoken = timestampSigner.sign(userId)
    accesstoken = timestampSigner.sign(“”)
    gLog.debug(“userId=%s -> accesstoken=%s”, userId, accesstoken)
    return accesstoken
def genAccesstokenKey(userId):
    return “%s|%s|%s”%(server_type, server_mode, userId)
        accesstokenKey = genAccesstokenKey(existedUser.id)
        gLog.debug(“accesstokenKey=%s”, accesstokenKey)
        #accesstoken = genAccesstoken(existedUser.id)
        accesstoken = genAccesstoken()
        gLog.debug(“accesstoken=%s”, accesstoken)

传入:

{
    “phone” : “13822224444”,
    “password” : “123456”,
    “type”    : “phone”
}

输出:

{
  “code”: 200,
  “data”: “.Ct5CCQ.q-nH8uHvz_fXQhCZWqgCsL0lrXg”,
  “message”: “user login OK”
}

不过,还是觉得不够好:

也担心,万一,用户数多了,大规模并发的话,则此处的通过timestamp而生成的token,会不会由于同一时刻的time是一样的,比如即使精确到毫秒,那同一时刻,time也是一样的,从而导致生成的token会冲突了

-》所以,打算换用参考别人的:

纯粹随机的值

比如:

python Erlang,Java,Groovy,javascript等语言生成随机密码 – 为程序员服务

SecureRandom random = new SecureRandom();
    String str = new BigInteger(130, random).toString(32);
import string,random
def makePassword(minlength=5,maxlength=25):
  length=random.randint(minlength,maxlength)
  letters=string.ascii_letters+string.digits # alphanumeric, upper and lowercase
  return ”.join([random.choice(letters) for _ in range(length)])

去试试

【总结】

最后是:

<code>############################################################
# Configuration
############################################################
LOGIN_ACCESS_TOKEN_EXPIRED_SECONDS = 60*60*24
# LOGIN_ACCESS_TOKEN_EXPIRED_SECONDS = 30

LOGIN_ACCESS_TOKEN_LEN = 32

PREFIX_ACCESS_TOKEN = "accesstoken"


############################################################
# Constant
############################################################

# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
DIGITS = string.digits
ASCII_LETTERS = string.ascii_letters
ALPHANUMERIC_LETTERS = ASCII_LETTERS + DIGITS

### random number and string
def genRandomStr(choiceStr, length):
    randomStr = ''.join([random.choice(choiceStr) for _ in range(length)])
    return randomStr

def genRandomAlphanum(length):
    randomAlphanum = genRandomStr(ALPHANUMERIC_LETTERS, length=length)
    return randomAlphanum

############################################################
# Function
############################################################

def genAccesstoken(tokenLen=LOGIN_ACCESS_TOKEN_LEN):
    return genRandomAlphanum(tokenLen)
</code>

即可生成access token,其实就是,确保不会重复的随机字符串。

转载请注明:在路上 » 【已解决】Flask中如何设计和生成用户访问控制的access token

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
60 queries in 0.103 seconds, using 18.37MB memory