python flask token token principle and code implementation

token authentication token

If you think there is a lot of nonsense, you can directly look at the code
Code reference: http://t.csdn.cn/Sf8km

What problem does token token solve

Solve the stateless feature of http requests, let each request have a state, and know which user sent the request

The first thing to know is that http requests are stateless
In other words, even if there are two requests sent by the same person, the server does not know that the same person came to visit.
So if you want the server to know who the requesting user is, you need to use token token technology

It is equivalent to forcibly adding a state to the http request

understand

What is the role of ancient tokens?
1. The technology of making tokens can only be made by the emperor, and no one else can fake it
2. The token represents a certain person, seeing the token is like seeing a person

In fact, the token technology of the interface is the same as the concept of the ancient token
1. The token token can only be made by the web server, and cannot be counterfeited by others
2. The user's information is stored in the token, and the server knows which user's token the token is after decrypting the token

principle

1. After each successful login, the server encrypts the current user id, generates a token, and returns it to the client
2. Every time the customer visits with a token, the server checks the token, and can take out the user id inside, and then know which user is accessing

It should be noted that the operation of generating a token can only be generated and decrypted by the server. If others know your token generation and decryption, they can forge the token

question

Think about the current strategy, whether it can satisfy the single sign-on function

Even if there are three different people at the same time, log in one after another, get the token, and then go to visit, the server will not know
Because the information stored in the token is only the user's id, the server also judges whether the token is valid based on the user's id
And the user id cannot be changed, a user id may be associated with other data

Solution 1

1. New fields added to the database, login timestamp
2. Every time the user logs in, update the login timestamp
3. In the encrypted token, add a login timestamp field to record the login timestamp currently recorded by the user
4. The user sends a request to check whether the login time stamp in the token is consistent with the database. If not, it means that someone else has logged in, and the returned token is invalid

Solution 2

1. Add new fields to the database, token
2. Every time a user logs in, a uuid is generated and recorded in the token field of the user database (uuid will not be repeated)
3. In the encrypted token token, replace the user id with the token field of the database
4. The user sends a request, check the token field in the token, go to the database to search, and the user is found. If not found, the token has been updated, and the returned token is invalid

the code

In python, there are three ways to generate tokens

1.pyjwt
import jwt  
  
# The secret key to generate the token  
secret_key = "aixlti5oa#xh8untx"  
  
# generate token  
def create_token(data, key):  
    return jwt.encode(data, key, algorithm="HS256")  
  
  
# decryption token  
def open_token(token, key):  
    try:  
        return jwt.decode(token, key, algorithms=["HS256"])  
    except:  
        return None  
  
  
# Simulate user login, make token with user id information, and return to app  
user_info = {"user_id": 123}  
user_token = create_token(user_info, secret_key)  
print(user_token)  
  
# User request, check if there is a user id in the token, if not, the token is forged  
result = open_token(user_token, secret_key)  
print(result)
2. Use a lower version of itsdangerous library
from itsdangerous import TimedSerializer as Serializer
from itsdangerous import BadSignature, SignatureExpired


def generate_token(user, operation, **kwargs):
    """Generated for email verification JWT(json web token)"""
    s = Serializer(current_app.config['SECRET_KEY'], expire_in)

    # payload to be signed
    data = {'id': user.id, 'operation': operation}
    data.update(**kwargs)
    return s.dumps(data)

def validate_token(user, token, operation):
    """Used to verify user registration token, And complete the corresponding confirmation operation"""
    s = Serializer(current_app.config['SECRET_KEY'])

    try:
        data = s.loads(token)
    except (SignatureExpired, BadSignature):
        return False
    ... # Relevant field confirmation
    return True
--------
Copyright statement: This article is CSDN blogger「empty nesters_rui」The original article, follow CC 4.0 BY-SA Copyright agreement, please attach the original source link and this statement for reprinting.
Original link: https://blog.csdn.net/weixin_43863487/article/details/123784400
3.authlib
from authlib.jose import jwt, JoseError

def generate_token(user, operation, **kwargs):
    """Generated for email verification JWT(json web token)"""
    # signature algorithm
    header = {'alg': 'HS256'}
    # key used for signing
    key = current_app.config['SECRET_KEY']
    # payload to be signed
    data = {'id': user.id, 'operation': operation}
    data.update(**kwargs)

    return jwt.encode(header=header, payload=data, key=key)


def validate_token(user, token, operation):
    """Used to verify user registration and user modification of password or email address token, And complete the corresponding confirmation operation"""
    key = current_app.config['SECRET_KEY']

    try:
        data = jwt.decode(token, key)
        print(data)
    except JoseError:
        return False
    ... # Confirmation of other fields
    return True

Tags: Python server Web Security Flask

Posted by Access on Sat, 04 Feb 2023 17:18:03 +0530