在某些情况下,您可能希望同时为受保护和不受保护的数据使用一个endpoint.在这些情况下,可以使用jwt_optional()
装饰器。这将允许访问端点而不管JWTtoken是否随请求一起发送.如果在请求中发送了一个已过期或构造错误的JWT,则将返回一个错误,由用户决定下一步如何进行,而不是直接范围response错误。
from flask import Flask, jsonify, request
from flask_jwt_extended import (
JWTManager, jwt_optional, create_access_token,
get_jwt_identity
)
app = Flask(__name__)
# Setup the Flask-JWT-Extended extension
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 not username:
return jsonify({"msg": "Missing username parameter"}), 400
if not password:
return jsonify({"msg": "Missing password parameter"}), 400
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), 200
@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
if __name__ == '__main__':
app.run()
网友评论