当前位置:   article > 正文

flask 实现token生成以及携带token请求接口_flask-jwt

flask-jwt

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

提示:这里可以添加本文要记录的大概内容:


提示:以下是本篇文章正文内容,下面案例可供参考

一、Flask-JWT-Extended是什么?

示例:flask服务中使用生成token验证,携带token请求接口;设置token过期时间等.

二、使用步骤

1.引入库

pip install flask-jwt-extended

代码如下(示例):

from flask import Flask, request, jsonify
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity,JWTManager,create_refresh_token
from flask import Flask, request, Blueprint
from datetime import timedelta
import json

# 安装 token 设置登录token验证
# pip install flask-jwt-extended


user_blueprint = Blueprint('user_blueprint', __name__)


@user_blueprint.route('/login', methods=['POST'])
def login():
    username = request.json.get('username', None)
    password = request.json.get('password', None)

    if username != 'admin' or password != 'admin':
        return jsonify({"msg": "Bad username or password",'code':401}), 401

    access_token = create_access_token(identity=username)
    refresh_token = create_refresh_token(identity=username)

    rest = {
        'access_token': f"Bearer {access_token}",
        'refresh_token': f"Bearer {refresh_token}",
        'code': 200
    }
    # return jsonify(access_token=access_token), 200
    # return jsonify(rest)
    return json.dumps(rest, ensure_ascii=False)


@user_blueprint.route('/protected', methods=['GET'])
@jwt_required()
def protected():
    current_user = get_jwt_identity()
    print(current_user)
    # return jsonify({'msg': 'ok'}), 200
    return jsonify({'msg': 'ok'})


# 使用刷新JWT来获取普通JWT  前提是已经调用了 /login 接口 携带 refresh_token请求该接口
@user_blueprint.route("/refresh", methods=["POST"])
@jwt_required(refresh=True)
def refresh():
    identity = get_jwt_identity()
    access_token = create_access_token(identity=identity)
    rest = {
        'access_token': f"Bearer {access_token}",
        'code': 200
    }
    return jsonify(rest)


def create_app():
    app = Flask(__name__)

    app.secret_key = 'ChangeMe!'
    # app.config['JWT_SECRET_KEY'] = 'my_secret_key'
    app.config['JWT_BLACKLIST_ENABLED'] = True
    app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access']
    # 设置普通JWT过期时间
    app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(seconds=30)
    # 设置刷新JWT过期时间
    app.config["JWT_REFRESH_TOKEN_EXPIRES"] = timedelta(days=30)
    jwt = JWTManager(app)
    jwt.init_app(app)
    app.register_blueprint(user_blueprint)
    return app


app = create_app()

if __name__ == '__main__':
    # app.run()
    app.run(debug=True, port='8888')


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80

2.请求验证

代码如下(示例):

import requests
import json


url = 'http://127.0.0.1:8888/login'
data = {'username': 'admin',
        'password': 'admin'}

headers1 = {'Content-Type': 'application/json'}
data = json.dumps(data)
ret = requests.post(url=url, data=data, headers=headers1)
access_token = ret.json()['access_token']
refresh_token = ret.json()['refresh_token']
print(access_token)
print(refresh_token)


access_token = 'Bearer vvv'
refresh_token = 'Bearer xxx'

# ==============以下验证token
url2 = 'http://127.0.0.1:8888/protected'
token = access_token
params = {}
headers2 = {
        # 'Content-Type': 'application/json',
        'Authorization': token}
ret2 = requests.get(url=url2,headers=headers2,params=params)
print(ret2.json())

# ==============以下刷新token

# url3 = 'http://127.0.0.1:8888/refresh'
# token = refresh_token
# headers2 = {
#         # 'Content-Type': 'application/json',
#         'Authorization': token}
# ret3 = requests.post(url=url3,headers=headers2)
# print(ret3.json()['access_token'])

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

该处使用的url网络请求的数据。


总结

提示:这里对文章进行总结:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/570728
推荐阅读
相关标签
  

闽ICP备14008679号