flask_jwt_extended

一.基本用法

最基础的用法不需要很多的调用,只需要使用三个函数:
1. create_access_token()用来创建令牌
2. get_jwt_identity()用来根据令牌取得之前的identity信息
3. jwt_required()这是一个装饰器,用来保护flask节点
官方的代码如下:
from flask import Flask
from flask import jsonify
from flask import request

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

app = Flask(__name__)

# Setup the Flask-JWT-Extended extension
app.config["JWT_SECRET_KEY"] = "super-secret"  # Change this!
jwt = JWTManager(app)


# Create a route to authenticate your users and return JWTs. The
# create_access_token() function is used to actually generate the JWT.
@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

    access_token = create_access_token(identity=username)
    return jsonify(access_token=access_token)


# Protect a route with jwt_required, which will kick out requests
# without a valid JWT present.
@app.route("/protected", methods=["GET"])
@jwt_required()
def protected():
    # Access the identity of the current user with get_jwt_identity
    current_user = get_jwt_identity()
    return jsonify(logged_in_as=current_user), 200


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

二.可选的路由保护

# 对于一个路由节点,授权和未授权的均可以访问,但会使用不同的功能,
# 这个时候就要使用jwt_optional()装饰器,
# 至于判断是否是有token的用户,可以根据get_jwt_identity()函数的返回值判断
@app.route('/partially-protected', methods=['GET'])
@jwt_optional
def partially_protected():
    # If no JWT is sent in with the request, get_jwt_identity()
    # will return None
    current_user = get_jwt_identity()
    if current_user:
        return jsonify(logged_in_as=current_user), 200
    else:
        return jsonify(logged_in_as='anonymous user'), 200

三.访问令牌中存储数据

除去存放基本的用户的标识identity外,在access_token中还可能存放其他的信息,

1. user_claims_loader()用于将信息存储到access_token中,例子中的注释提到

该函数在create_access_token()函数被调用后使用,参数是创建令牌的参数identity

2. get_jwt_claims()用于在被包含的节点内获取access_token的信息

该函数在creat_access_token()被调用后使用

@jwt.user_claims_loader
def add_claims_to_access_token(identity):
    return {
        'hello': identity,
        'foo': ['bar', 'baz']
    }

# In a protected view, get the claims you added to the jwt with the
# get_jwt_claims() method
@app.route('/protected', methods=['GET'])
@jwt_required
def protected():
    claims = get_jwt_claims()
    return jsonify({
        'hello_is': claims['hello'],
        'foo_is': claims['foo']
    }), 200
posted @ 2021-08-03 16:03  wuyuan2011woaini  阅读(322)  评论(0编辑  收藏  举报