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

相关推荐
毕设源码-郭学长14 分钟前
【开题答辩全过程】以 基于Python爬取学院师资队伍信息的设计与分析为例,包含答辩的问题和答案
开发语言·python
aihuangwu26 分钟前
ChatGPT和Gemini图表怎么导出
人工智能·ai·chatgpt·deepseek·ds随心转
2301_7657031428 分钟前
工具、测试与部署
jvm·数据库·python
Jackson@ML28 分钟前
Kimi K2.5横空出世!K2.5模型功能详解
python·大语言模型·kimi
好好研究29 分钟前
SpringBoot整合SpringMVC
xml·java·spring boot·后端·mvc
BYSJMG33 分钟前
计算机毕设选题推荐:基于大数据的癌症数据分析与可视化系统
大数据·vue.js·python·数据挖掘·数据分析·课程设计
曹轲恒33 分钟前
SpringBoot整合SpringMVC(末)
java·spring boot·后端
小马爱打代码35 分钟前
Spring Boot:邮件发送生产可落地方案
java·spring boot·后端
我材不敲代码41 分钟前
Python爬虫介绍——简单了解一下爬虫
开发语言·爬虫·python
naruto_lnq1 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python