直接上代码
from flask import Flask, jsonify, request, make_response
import jwt
import datetime
from functools import wrapsapp = Flask(__name__)# 这是一个示例密钥,实际应用中应该使用一个复杂且随机的密钥
app.config['SECRET_KEY'] = 'your_secret_key'def token_required(f):@wraps(f)def decorated(*args, **kwargs):token = Noneif 'Authorization' in request.headers:auth_header = request.headers['Authorization']if auth_header.startswith('Bearer '):token = auth_header.split(" ")[1] # 分割"Bearer "和tokenif not token:return jsonify({'message': 'Token is missing!'}), 403try:data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])except:return jsonify({'message': 'Token is invalid!'}), 403return f(*args, **kwargs)return decorated@app.route('/unprotected')
def unprotected():return jsonify({'message': 'Anyone can view this!'})@app.route('/protected')
@token_required
def protected():return jsonify({'message': 'This is only available for people with valid tokens.'})@app.route('/login')
def login():auth = request.authorizationif auth and auth.password == 'password':token = jwt.encode({'user': auth.username,'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, app.config['SECRET_KEY'])return jsonify({'token': token})return make_response('Could not verify!', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})if __name__ == '__main__':app.run(debug=True)
测试,登录,获取token
curl -u username:password http://127.0.0.1:5000/login返回{"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoidXNlcm5hbWUwIiwiZXhwIjoxNzA4MzkyNjg5fQ.0Xq-GFufOTnLSkdqT42wVcF0QPe70z6tlxepwWzHf7Y"
}
用token 测试/protected
curl -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoidXNlcm5hbWUwIiwiZXhwIjoxNzA4MzkyNjg5fQ.0Xq-GFufOTnLSkdqT42wVcF0QPe70z6tlxepwWzHf7Y" http://127.0.0.1:5000/protected返回信息{"message": "This is only available for people with valid tokens."
}
chatgpt写的代码