前端传给你用户id和token
作为后端,你要进行思索
1.如果一开始传过来的token为空(即用户第一次使用这个功能),你要生成一个token并返回
2.如果token不为空,你要对这个token进行解密:看解密后的用户id与传过来的id是否对的上,如果对的上,则返回你想返回的东西,如果对不上,则返回error
3.解密后的时间对的上吗,如果token你设置的有效时间是2小时,过期了,就要重新返回一个新的token
对应的后端代码
from flask import Blueprint, request, jsonify, render_template
import hashlib
import time
import base64
login_bp = Blueprint('login', __name__)
@login_bp.route('/')
def index():
return render_template('login/index.html')
@login_bp.route('/login', methods=['POST'])
def login():
data = request.get_json()
user_id = data.get('user_id')
token = data.get('token')
if not user_id:
return jsonify({'error': 'User ID is required'}), 400
# 打印调试信息
print(f"Received user_id: {user_id}, token: {token}")
if not token:
# 生成新的Token
new_token = generate_token(user_id)
return jsonify({'token': new_token})
else:
# 验证Token
decrypted_user_id, timestamp = decrypt_token(token)
if decrypted_user_id is None:
return jsonify({'error': 'Invalid token'}), 401
current_time = int(time.time())
if current_time - timestamp > 43200:#过期的时间,以秒为单位,这里以12小时为单位
# Token已过期,重新生成Token
new_token = generate_token(user_id)
return jsonify({'error': 'Token has expired', 'token': new_token})
if decrypted_user_id == user_id:
return jsonify({'message': 'successful'})
else:
return jsonify({'error': 'Invalid token'}), 401
@login_bp.route('/test', methods=['GET'])
def test():
return 'Test route is working'
def generate_token(user_id):
# 生成包含用户ID和当前时间戳的Token
token_str = f"{user_id}:{int(time.time())}"
token = base64.b64encode(token_str.encode()).decode()
return token
def decrypt_token(token):
# 解密Token,返回用户ID和时间戳
try:
token_str = base64.b64decode(token.encode()).decode()
user_id, timestamp = token_str.split(':')
return user_id, int(timestamp)
except Exception as e:
print(f"Error decrypting token: {e}")
return None, None
curl命令进行测试
curl -X POST http://localhost:5000/login/login -H "Content-Type: application/json" -d '{"user_id": "1", "token": ""}'
curl -X POST http://localhost:5000/login/login -H "Content-Type: application/json" -d '{"user_id": "1", "token": "MToxNzIxMDYxOTkx"}'
curl -X POST http://localhost:5000/login/login -H "Content-Type: application/json" -d '{"user_id": "1", "token": "MToxNzIxMDYxOT"}'