python3 Flask jwt 简易token认证实例

直接上代码

复制代码
from flask import Flask, jsonify, request, make_response
import jwt
import datetime
from functools import wraps

app = Flask(__name__)

# 这是一个示例密钥,实际应用中应该使用一个复杂且随机的密钥
app.config['SECRET_KEY'] = 'your_secret_key'

def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = None
        if 'Authorization' in request.headers:
            auth_header = request.headers['Authorization']
            if auth_header.startswith('Bearer '):
                token = auth_header.split(" ")[1]  # 分割"Bearer "和token

        if not token:
            return jsonify({'message': 'Token is missing!'}), 403

        try:
            data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
        except:
            return jsonify({'message': 'Token is invalid!'}), 403

        return 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.authorization
    if 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写的代码

相关推荐
我命由我1234526 分钟前
智能助手通用问答边界
人工智能·python·学习·ai·学习方法·ai编程·智能体
Angeldream1231 小时前
第 4 章 医学影像预处理
图像处理·人工智能·python·医学影像·医学影像处理
Web3&Basketball1 小时前
实测Gemini4Argon:ERQA 87%登顶长程任务榜
数据库·python·大模型·多模态·gemini·长上下文·推理优化
tianbin9111 小时前
大模型训练与推理:API中转站在企业AI落地中的隐藏价值
大数据·后端·ai
把我格子衫拿来1 小时前
医学影像重采样:spacing 改了,为什么模型位置也跟着错了?
python·dicom·医学影像·simpleitk·重采样
打工仔折腾 AI1 小时前
用 Dashlet 把极空间 NAS 服务入口整理成统一导航首页的实践
java·开发语言·人工智能·后端·python·rpc·ai agent 实战
wuyk5552 小时前
PyQt6-第05讲-QtDesigner工作流与ui文件
python·ui·pyqt
Want5952 小时前
Python跳动的爱心②
开发语言·python·数学建模
田里的水稻2 小时前
PyTorch_TensorBoard展示
人工智能·pytorch·python·深度学习·神经网络