除非有人告诉我更好的方法,否则我最终会修补该decode_token
功能:
我突出显示了“已修补”区域,该区域拦截了“ExpiredSignatureError”,并检查该 IP 地址是否在用户 ip-whitelist 中,如果是,则允许照常营业。
def decode_token(encoded_token, csrf_value=None, allow_expired=False):
"""
Returns the decoded token (python dict) from an encoded JWT. This does all
the checks to insure that the decoded token is valid before returning it.
:param encoded_token: The encoded JWT to decode into a python dict.
:param csrf_value: Expected CSRF double submit value (optional)
:param allow_expired: Options to ignore exp claim validation in token
:return: Dictionary containing contents of the JWT
"""
jwt_manager = _get_jwt_manager()
unverified_claims = jwt.decode(
encoded_token, verify=False, algorithms=config.decode_algorithms
)
unverified_headers = jwt.get_unverified_header(encoded_token)
# Attempt to call callback with both claims and headers, but fallback to just claims
# for backwards compatibility
try:
secret = jwt_manager._decode_key_callback(unverified_claims, unverified_headers)
except TypeError:
msg = (
"The single-argument (unverified_claims) form of decode_key_callback ",
"is deprecated. Update your code to use the two-argument form ",
"(unverified_claims, unverified_headers)."
)
warn(msg, DeprecationWarning)
secret = jwt_manager._decode_key_callback(unverified_claims)
try:
return decode_jwt(
encoded_token=encoded_token,
secret=secret,
algorithms=config.decode_algorithms,
identity_claim_key=config.identity_claim_key,
user_claims_key=config.user_claims_key,
csrf_value=csrf_value,
audience=config.audience,
issuer=config.issuer,
leeway=config.leeway,
allow_expired=allow_expired
)
except ExpiredSignatureError:
expired_token = decode_jwt(
encoded_token=encoded_token,
secret=secret,
algorithms=config.decode_algorithms,
identity_claim_key=config.identity_claim_key,
user_claims_key=config.user_claims_key,
csrf_value=csrf_value,
audience=config.audience,
issuer=config.issuer,
leeway=config.leeway,
allow_expired=True
)
# ------------------------------------------------------------
# Author: Nicholas E. Hamilton
# Date: 25th August 2019
# Patch: Check if ip address is in the whitelist,
# and if so, permit an expired token
# ------------------------------------------------------------
user = user_loader(expired_token[config.identity_claim_key])
ip_address = request.remote_addr
if user and ip_address:
ip_whitelist = [x.ip_address for x in user.ip_whitelist]
if ip_address in ip_whitelist:
return expired_token
# >>>> END PATCH
# Proceed as normal
ctx_stack.top.expired_jwt = expired_token
raise
flask_jwt_extended.view_decorators.decode_token = flask_jwt_extended.utils.decode_token = decode_token