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("首页")
   
相关推荐
列逍6 分钟前
博客系统测试
自动化测试·python·性能测试
星栈8 分钟前
深度复盘:比 EventLoop 更隐蔽!Node 微任务堆积引发的线上接口雪崩事故
后端·node.js
名字还没想好☜1 小时前
Go slice 的 append 陷阱:共享底层数组导致的数据串改
开发语言·后端·golang·go·slice
诸神缄默不语1 小时前
FastAPI后端配置CORS中间件支持浏览器跨域访问
后端·fastapi
Fanta丶1 小时前
14.Activiti7 网关 排他网关ExclusiveGateway、并行网关ParallelGateway
后端
星云开发1 小时前
拒绝无效加班!用Python打造自动化办公流,附Word/PDF互转硬核代码
python
明月_清风1 小时前
robots.txt 完全指南:从入门到精通
后端·爬虫
jvmind_dev1 小时前
Java GC 实战指南(番外篇):被忽视的隐形杀手 —— Class Unloading 如何拖垮 GC
java·后端
明月_清风1 小时前
从零写一个"像人"的爬虫:反爬攻防实战指南
后端·爬虫
贰先生1 小时前
Xiuno BBS 审计之问题13:管理员发帖 doctype=0 时存储型 XSS
后端