python - 如何将刷新 token 发布到 Flask JWT Extended?

标签 python flask flask-jwt-extended

我正在尝试通过此处的代码刷新 JWT token 。问题在于如何通过刷新获取新 token 。

这个有效:

curl http://127.0.0.1:5000/protected
{"msg":"Missing Authorization Header"}

这有效,我得到了我的 token 并将其放入 ACCESS

curl -H "Content-Type: application/json" -X POST   -d '{"username":"test","password":"test"}' http://localhost:5000/login

这有效,我得到了我的用户名

curl -H "Authorization: Bearer $ACCESS" http://localhost:5000/protected

但是当 token 过期时,我如何使用我的刷新 token 和/或访问 token 进行 curl 以获取我的新访问 token ?我尝试了很多 POST,但似乎没有任何效果:

https://flask-jwt-extended.readthedocs.io/en/latest/refresh_tokens.html

from flask import Flask, jsonify, request
from flask_jwt_extended import (
    JWTManager, jwt_required, create_access_token,
    jwt_refresh_token_required, create_refresh_token,
    get_jwt_identity
)

app = Flask(__name__)

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


@app.route('/login', methods=['POST'])
def login():
    username = request.json.get('username', None)
    password = request.json.get('password', None)
    if username != 'test' or password != 'test':
        return jsonify({"msg": "Bad username or password"}), 401

    # Use create_access_token() and create_refresh_token() to create our
    # access and refresh tokens
    ret = {
        'access_token': create_access_token(identity=username),
        'refresh_token': create_refresh_token(identity=username)
    }
    return jsonify(ret), 200


# The jwt_refresh_token_required decorator insures a valid refresh
# token is present in the request before calling this endpoint. We
# can use the get_jwt_identity() function to get the identity of
# the refresh token, and use the create_access_token() function again
# to make a new access token for this identity.
@app.route('/refresh', methods=['POST'])
@jwt_refresh_token_required
def refresh():
    current_user = get_jwt_identity()
    ret = {
        'access_token': create_access_token(identity=current_user)
    }
    return jsonify(ret), 200


@app.route('/protected', methods=['GET'])
@jwt_required
def protected():
    username = get_jwt_identity()
    return jsonify(logged_in_as=username), 200


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

最佳答案

尝试

curl -H "Authorization: Bearer $REFRESH" -X POST http://localhost:5000/refresh

关于python - 如何将刷新 token 发布到 Flask JWT Extended?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55089892/

相关文章:

python - 你如何访问 Flask 路由中的查询字符串?

python - 使用模板渲染实现 flask_jwt_extended

flask - 如何在flask-jwt-extended的redis中存储jwt token ?

java - 在 Java 中使用 Python 创建的 JWT Token

python - 如何获取 Jinja2 模板中的参数列表

python-3.x - 如何在 Gunicorn 启动其主进程之前触发函数

python - 如何检测矩形对象、图像或 Sprite 何时被单击

python - Python 中的 Bokeh 包 : How to use rgb to color option

Python3.4 Py2exe,报错-name 'WinDLL' is not defined

python - 如何在 Django 中显示自定义 404.html 页面