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写的代码

相关推荐
闲人编程2 小时前
Python在网络安全中的应用:编写一个简单的端口扫描器
网络·python·web安全·硬件·端口·codecapsule·扫描器
星释3 小时前
Rust 练习册 :Leap与日期计算
开发语言·后端·rust
Mr_Xuhhh5 小时前
GUI自动化测试--自动化测试的意义和应用场景
python·集成测试
2301_764441335 小时前
水星热演化核幔耦合数值模拟
python·算法·数学建模
循环过三天5 小时前
3.4、Python-集合
开发语言·笔记·python·学习·算法
Q_Q5110082855 小时前
python+django/flask的眼科患者随访管理系统 AI智能模型
spring boot·python·django·flask·node.js·php
码事漫谈7 小时前
C++死锁深度解析:从成因到预防与避免
后端
SunnyDays10117 小时前
如何使用Python高效转换Excel到HTML
python·excel转html
码事漫谈7 小时前
智能体颠覆教育行业:现状、应用与未来展望调研报告
后端
蓝-萧7 小时前
【玩转全栈】----Django基本配置和介绍
java·后端