Introduction of token and several methods of generating token with python

basic concept

Token means "token" in Chinese. Mainly used for authentication. Big sites like Facebook, Twitter, Google+, Github are all in use. Compared with traditional authentication methods, Token has the characteristics of strong scalability and high security, and is very suitable for use in web applications or mobile applications.

Authentication method

With the Token-based authentication method, there is no need to store the user's login record on the server. The approximate process is as follows:

  1.   客户端使用用户名跟密码请求登录
    
  2.   服务端收到请求,去验证用户名与密码
    
  3.   验证成功后,服务端会签发一个 Token,再把这个 Token 发送给客户端
    
  4.   客户端收到 Token 以后可以把它存储起来,比如放在 Cookie 里或者 Local Storage 里
    
  5.   客户端每次向服务端请求资源的时候需要带着服务端签发的 Token
    
  6.   服务端收到请求,然后去验证客户端请求里面带着的 Token,如果验证成功,就向客户端返回请求的数据
    

Commonly used Token generation methods in python

binascii.b2a_base64(os.urandom(24))[:-1]

Example of use:

import binascii

import them

binascii.b2a_base64(os.urandom(24))[:-1]

b’J1pJPotQJb6Ld+yBKDq8bqcJ71wXw+Xd’

The advantage of this algorithm is that the performance is fast, and the disadvantage is that there are special characters, which need to be replaced to do processing.

sha1(os.urandom(24)).hexdigest()

Example of use:

import hashlib

import them

hashlib.sha1(os.urandom(24)).hexdigest()

'21b7253943332d0237a720701bcb8161b82db776'

The advantage of this algorithm is that it is safe and requires no special handling. The downside is that the coverage is a bit poor.

uuid4().hex

Example of use:

import them

import uuid

uuid.uuid4().hex

'c58a80d3b7864b0686757b95e9626e47'

Uuid is more convenient to use, but the disadvantage is that it is slightly less secure.

base64.b32encode(os.urandom(20))/base64.b64encode(os.urandom(24))

import base64

import them

base64.b32encode(os.urandom(20))

b’NJMTBMOYIXHNRATTOTVONT4BXJAC25TX’

base64.b64encode(os.urandom(24))

b’l1eU6UzSlWsowm8M8lH5VaFhZEAQ4kQj’

Special Note:

  1. Where base64 can be used, binascii.b2a_base64 is a good choice - according to the definition of identifier in W3's SessionID string, base64 is used in SessionID, but it is necessary to pay attention to the special "=" when using it in the value of Cookie the presence of characters;

  2. If you want secure characters (alphanumerics), SHA1 is also a good choice with good performance;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324343470&siteId=291194637