get_jwt_identity() 在 Flask-JWT-Extended 中返回 None
Posted
技术标签:
【中文标题】get_jwt_identity() 在 Flask-JWT-Extended 中返回 None【英文标题】:get_jwt_identity() returning None in Flask-JWT-Extended 【发布时间】:2019-07-19 10:48:03 【问题描述】:我正在使用 Flask-JWT-Extended 来保护我的 Flask API。登录后,在受保护的路由(添加用户)中,我调用 get_jwt_identity(),但它返回 None,所以我无法获取身份。
@flask_app.route('/<api_version>/login', methods=['POST'])
def login(api_version):
print(f'login', request.form)
response = None
try:
username = request.form['username']
password = request.form['password']
if not username:
return jsonify("msg": "Missing username parameter"), 400
if not password:
return jsonify("msg": "Missing password parameter"), 400
user = User.get_with_password(username, password)
if (not user):
e1 = Unauthorized(
'Invalid username or password. Please try again.')
e1.status = 401
raise e1
""" flask_login.login_user(user, remember=True) """
access_token = create_access_token(identity=username)
response = json.dumps("token": access_token, cls=CustomJSONEncoder)
except Exception as e:
errMsg = f'Error Logging in user username if username else "": e'
status = e.status if hasattr(e, 'status') else 500
print(f'errMsg')
traceback.print_exc()
return Response(
json.dumps("message": errMsg, "status": status, "stack": traceback.format_exc() ), status=status, mimetype='application/json')
resp = Response(response, status=200, mimetype='application/json')
return resp
@flask_app.route('/<api_version>/add-user', methods=['POST'])
@jwt_required
def add_user(api_version):
print(f'add-user', request)
response = None
username = None
password = None
allow_admin = None
try:
data = request.get_json()
print(f'add-user data', data)
if 'username' in data:
username = data['username']
else:
return jsonify("msg": "Missing username parameter"), 400
if 'password' in data:
password = data['password']
else:
return jsonify("msg": "Missing password parameter"), 400
if 'allow_admin' in data:
allow_admin = data['allow_admin']
""" user = User.get_with_password(username, password)"""
user = get_jwt_identity()
print('user',user)
if (not user):
e1 = Unauthorized(
'Invalid username or password. Please try again.')
e1.status = 401
raise e1
response = json.dumps("user": user, cls=CustomJSONEncoder)
except Exception as e:
errMsg = f'Error Adding User username: e'
status = e.status if hasattr(e, 'status') else 500
print(f'errMsg')
traceback.print_exc()
return Response(
json.dumps("message": errMsg, "status": status, "stack": traceback.format_exc() ), status=status, mimetype='application/json')
resp = Response(response, status=200, mimetype='application/json')
return resp
用户.py
class User():
@classmethod
def get_with_password(cls, username, password):
print(f'User get_with_password username with password')
user_db = account.get_account(username)
print(f'User returned from DB: user_db')
user = User()
if not user_db or not len(user_db) or (not 'password' in user_db):
return None
user.username = username
user.id = username
if bcrypt.check_password_hash(user_db['password'], password):
user.role = user_db['role']
#user.is_authenticated = True
print(
f'loginUser returning vars(user) ')
return user
return None
【问题讨论】:
登录后尝试打印访问令牌,以及访问受保护功能add_user
时,看看它是否可用!如果不是,它应该引发一个丢失的令牌错误,而不是只返回 None!
【参考方案1】:
我也遇到了同样的问题,就我而言,我忘了添加@jwt_required
@jwt_required
def get(self):
uid = get_jwt_identity()
print("self.uid",uid)
在你的代码中有@jwt_required,检查可能是令牌已过期
【讨论】:
【参考方案2】:我也遇到了同样的问题,通过以下步骤解决了
第 1 步:检查您是否已将应用 (flask_app) 包装如下。
from flask_jwt_extended import JWTManager
jwt = JWTManager(flask_app)
第 2 步:检查您的应用中是否有 JWT_BLACKLIST_ENABLED。
如果您的应用中不存在 JWT_BLACKLIST_ENABLED = False 或 JWT_BLACKLIST_ENABLED,请在您使用过 create_token_method() 的地方添加以下方法(在您的情况下,它是登录方法)。
@jwt.user_claims_loader
def add_claims_to_access_token(identity):
return
'identity': identity
如果 JWT_BLACKLIST_ENABLED = True 然后在您的登录方法上方添加以下内容。
@jwt.token_in_blacklist_loader
def check_if_token_in_blacklist(decrypted_token):
jti = decrypted_token['jti']
return jti in blacklist
【讨论】:
以上是关于get_jwt_identity() 在 Flask-JWT-Extended 中返回 None的主要内容,如果未能解决你的问题,请参考以下文章
部署flas到服务器:No module named flask
资产监测设备中HCL190FLAS擦写问题分析——HCL190