flask处理token的装饰器

以下是在 Flask 中基于 token 实现的登录验证装饰器的示例代码:

python 复制代码
import jwt
from functools import wraps
from flask import request, jsonify, current_app

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        token = request.headers.get('Authorization')
        if not token:
            return jsonify({'message': 'Missing token'}), 401

        try:
            data = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
            current_user = data['username']
        except Exception as e:
            return jsonify({'message': 'Invalid token'}), 401

        return f(current_user, *args, **kwargs)

    return decorated_function

该装饰器首先检查请求头中是否存在 Authorization 字段,并解码其中的 token。如果没有找到 token,则返回一个包含错误消息的 JSON 响应。如果找到了 token,则使用 JWT 对其进行解码,同时使用 Flask 的 current_app 对象获取 SECRET_KEY。如果解码成功,那么装饰器会将解码出来的用户名传递给被装饰函数。如果解码失败,则返回一个包含错误消息的 JSON 响应。可以在需要登录验证的视图函数上添加该装饰器,例如:

python 复制代码
@app.route('/protected')
@login_required
def protected(current_user):
    return jsonify({'message': 'This is a protected endpoint for user {}'.format(current_user)})

在上述代码中,protected 视图函数被 @login_required 装饰器进行修饰,当用户成功登录后,该视图函数会返回一个包含当前用户信息的 JSON 响应。需要注意的是,已经登录的用户才能访问该视图函数,否则将返回一个包含错误消息的 JSON 响应。

不过以上内容中涉及了解密参数,如果token并未进行加密可以按照如下方式写:

python 复制代码
from functools import wraps
from flask import request, jsonify
def login_required_token(f):
    @functools.wraps(f)
    def decorated_function(*args, **kwargs):
        token = request.headers.get('Authorization')
        if not token:
            return jsonify({'message': 'Missing token'}), 401

        return f(*args, **kwargs)

    return decorated_function
python 复制代码
@app.route('/logaudit/program/', methods=["POST"])
@login_required_token
def program_log():
    # print("#"*50)
    # print("current user is:",current_user)
    return makeresponse("首页")
   
相关推荐
用户460438522508627 分钟前
关于 Paimon-Rust 的写操作(细节)
后端
掘金酱35 分钟前
AI 带来的新生意|稀土掘金 X-Lab 年度大会招募开启
前端·后端·vibecoding
nice_lcj5201 小时前
【从零理解计算机网络 · 02】分层模型:别背 OSI 七层,看数据怎么被“打包“和“拆包“
java·后端·tcp/ip·计算机网络·面试·osi·分层模型
SimonKing2 小时前
给Deepseek Harness装上插件市场,从此插件无忧
java·后端·程序员
kyle~2 小时前
FastAPI --- 将业务能力以 API 的形式提供给外部系统
python·fastapi·前后端
aiotto资源分享3 小时前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
利威尔xu3 小时前
Go Mutex 饥饿模式:正常模式等待者饿死,1ms 阈值自动切换崩溃
开发语言·后端·面试·golang·并发编程
一条Go3 小时前
边缘 Agent:为什么是它连出来,而不是平台连进去
后端·架构·github
huangfuyk4 小时前
前端融入/转后端避坑指南:AI 时代的安全边界、数据防线与实战细节
后端·ai编程
梯度下降者4 小时前
Python信号量,条件变量,事件学习
python·条件变量·事件·信号量·线程通信