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("首页")
   
相关推荐
我爱娃哈哈22 分钟前
Spring Cloud Gateway + 请求聚合(GraphQL-like):一次调用合并多个微服务响应
后端
曲幽27 分钟前
FastAPI + PostgreSQL 实战:给应用装上“缓存”和“日志”翅膀
redis·python·elasticsearch·postgresql·logging·fastapi·web·es·fastapi-cache
用户298698530141 小时前
C#:三行代码,给 Word 文档的文本框“一键清空”
后端·c#·.net
血小溅1 小时前
Claude Code Superpowers 插件基础教程
后端
树獭叔叔1 小时前
OpenClaw Agents 系统:多代理架构与智能编排的完整技术解析
后端·aigc·openai
蝎子莱莱爱打怪2 小时前
ESXi 强制断电后恢复CentOS7虚拟机避坑指南:解决重复注册&目录清理难题
linux·后端·程序员
ConardLi3 小时前
OpenClaw 完全指南:这可能是全网最新最全的系统化教程了!
前端·人工智能·后端
树獭叔叔3 小时前
OpenClaw Workspace 文件完整指南:从文件到 AI 行为的完整链路
后端·aigc·openai
Lupino3 小时前
别再只聊 AI 写代码了:技术负责人要把“变更治理”提到第一优先级
python·docker·容器
神奇小汤圆4 小时前
别死记硬背!Java的CountDownLatch 核心原理:AQS state 才是关键
后端