zl程序教程

您现在的位置是:首页 >  工具

当前栏目

Flask 学习-30.flask_jwt_extended 自定义 token 过期返回内容

学习 过期 自定义 内容 返回 30 JWT Flask
2023-06-13 09:12:01 时间

前言

flask_jwt_extended 插件使用,当token过期的时候,默认返回401 UNAUTHORIZED {"msg": "Token has expired"}

@jwt.expired_token_loader

设置一个回调函数,以便在过期时返回自定义响应令牌尝试访问受保护的路由。这个特定的回调函数 将jwt_header和jwt_payload作为参数,并且必须返回 Flask 响应。查看API文档以查看其他回调函数所需的参数和返回值。

官方文档使用示例

from flask import Flask
from flask import jsonify

from flask_jwt_extended import create_access_token
from flask_jwt_extended import jwt_required
from flask_jwt_extended import JWTManager

app = Flask(__name__)

app.config["JWT_SECRET_KEY"] = "super-secret"  # Change this!
jwt = JWTManager(app)

# Set a callback function to return a custom response whenever an expired
# token attempts to access a protected route. This particular callback function
# takes the jwt_header and jwt_payload as arguments, and must return a Flask
# response. Check the API documentation to see the required argument and return
# values for other callback functions.
@jwt.expired_token_loader
def my_expired_token_callback(jwt_header, jwt_payload):
    return jsonify(code="dave", err="I can't let you do that"), 401

@app.route("/login", methods=["POST"])
def login():
    access_token = create_access_token("example_user")
    return jsonify(access_token=access_token)

@app.route("/protected", methods=["GET"])
@jwt_required()
def protected():
    return jsonify(hello="world")

if __name__ == "__main__":
    app.run()

使用示例

token过期时,默认返回{"msg": "Token has expired"}, 使用@jwt.expired_token_loader 自定义token过期返回内容

@jwt.expired_token_loader
def my_expired_token_callback(jwt_header, jwt_payload):
    """返回 flask Response 格式"""
    return jsonify(code="401", err="token 已过期"), 401

重新访问带上一个过期token时

GET http://127.0.0.1:5000/api/v1/userinfo HTTP/1.1
User-Agent: Fiddler
Host: 127.0.0.1:5000
Content-Type: application/json
Content-Length: 0
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTY2MTk1NzA2NiwianRpIjoiNmY4NWRlNGEtZThhNS00ZGY2LWJiMjktMmM4NWQyMWE3ZjU3IiwidHlwZSI6ImFjY2VzcyIsInN1YiI6InRlc3Q1IiwibmJmIjoxNjYxOTU3MDY2LCJleHAiOjE2NjE5NjA2NjZ9.GKsz2nJUziXLWfYrzidX7Fopw5tlycT0lZBKlvnpt8s

HTTP/1.1 401 UNAUTHORIZED
Server: Werkzeug/2.2.2 Python/3.8.5
Date: Thu, 01 Sep 2022 03:11:58 GMT
Content-Type: application/json
Content-Length: 48
Connection: close

{
  "code": "401",
  "err": "token 已过期"
}

此时返回的内容就是我们自定义的

2022年第 12期《python接口web自动化+测试开发》课程,9月17号开学!

本期上课时间:2022年9月17号 - 2022年12月17号,周六周日上午9:00-11:00

报名费:报名费3000一人(周期3个月)

联系微信/QQ:283340479