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

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

文章目录

  • 前言
  • 一、Flask-JWT-Extended是什么?
  • 二、使用步骤
    • 1.引入库
    • 2.请求验证
  • 总结


前言

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


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

一、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')


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'])

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


总结

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

你可能感兴趣的:(flask,python,后端)