本文整理汇总了Python中jwt.ExpiredSignatureError方法的典型用法代码示例。如果您正苦于以下问题:Python jwt.ExpiredSignatureError方法的具体用法?Python jwt.ExpiredSignatureError怎么用?Python jwt.ExpiredSignatureError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jwt
的用法示例。
在下文中一共展示了jwt.ExpiredSignatureError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_transaction_from_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignatureError [as 别名]
def get_transaction_from_token(view):
def decorator(request, token):
try:
expired = False
transaction_uuid = jwt.decode(token,
settings.PAYMENT_METHOD_SECRET)['transaction']
except jwt.ExpiredSignatureError:
expired = True
transaction_uuid = jwt.decode(token, settings.PAYMENT_METHOD_SECRET,
options={'verify_exp': False})['transaction']
try:
uuid = UUID(transaction_uuid, version=4)
except ValueError:
raise Http404
Transaction = apps.get_model('silver.Transaction')
return view(request, get_object_or_404(Transaction, uuid=uuid), expired)
return decorator
示例2: authenticate
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignatureError [as 别名]
def authenticate(self, request):
"""
Returns a two-tuple of `User` and token if a valid signature has been
supplied using JWT-based authentication. Otherwise returns `None`.
"""
jwt_value = self._get_jwt_value(request)
if jwt_value is None:
return None
try:
payload = decode_jwt(jwt_value)
except jwt.ExpiredSignatureError:
msg = 'Signature has expired.'
raise exceptions.AuthenticationFailed(msg)
except jwt.DecodeError:
msg = 'Error decoding signature.'
raise exceptions.AuthenticationFailed(msg)
except jwt.InvalidTokenError:
raise exceptions.AuthenticationFailed()
self._add_session_details(request, payload)
user = self.authenticate_credentials(payload)
return user, JwtToken(payload)
示例3: validate
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignatureError [as 别名]
def validate(self):
"""Decodes the auth token and performs some preliminary validation."""
self.is_expired = False
self.is_valid = True
self.account_id = None
if self.jwt is None:
self.is_expired = True
else:
try:
payload = jwt.decode(self.jwt, self.secret)
self.account_id = payload['sub']
except jwt.ExpiredSignatureError:
self.is_expired = True
except jwt.InvalidTokenError:
self.is_valid = False
示例4: decode_auth_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignatureError [as 别名]
def decode_auth_token(auth_token, token_type='Auth'):
"""
Validates the auth token
:param auth_token:
:return: integer|string
"""
try:
payload = jwt.decode(auth_token, current_app.config.get(
'SECRET_KEY'), algorithms='HS256')
is_blacklisted_token = BlacklistToken.check_blacklist(auth_token)
if is_blacklisted_token:
return 'Token blacklisted. Please log in again.'
else:
return payload
except jwt.ExpiredSignatureError:
return '{} Token Signature expired.'.format(token_type)
except jwt.InvalidTokenError:
return 'Invalid {} Token.'.format(token_type)
示例5: decode_auth_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignatureError [as 别名]
def decode_auth_token(cls, token: str):
"""
验证token
:param token:
:return:
"""
key = current_app.config.get('SECRET_KEY', cls.key)
try:
# 取消过期时间验证
# payload = jwt.decode(auth_token, config.SECRET_KEY, options={'verify_exp': False})
payload = jwt.decode(token, key=key, )
except (jwt.ExpiredSignatureError, jwt.InvalidTokenError, jwt.InvalidSignatureError):
return None
else:
return payload
示例6: decode_auth_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignatureError [as 别名]
def decode_auth_token(self, auth_token):
"""
验证Token
:param auth_token:
:return: dict
"""
try:
payload = jwt.decode(auth_token, self.token_secret, algorithms=['HS256'],
leeway=datetime.timedelta(seconds=10))
if 'data' in payload and 'user_id' in payload['data']:
return payload['data']
else:
raise jwt.InvalidTokenError
except jwt.ExpiredSignatureError:
return dict(status=-1, msg='Token过期')
except jwt.InvalidTokenError:
return dict(status=-2, msg='无效Token')
示例7: decode_auth_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignatureError [as 别名]
def decode_auth_token(auth_token):
"""
Validates the auth token
:param auth_token:
:return: integer|string
"""
try:
payload = jwt.decode(auth_token, app.config.get('SECRET_KEY'))
is_blacklisted_token = BlacklistToken.check_blacklist(auth_token)
if is_blacklisted_token:
return 'Token blacklisted. Please log in again.'
else:
return payload['sub']
except jwt.ExpiredSignatureError:
return 'Signature expired. Please log in again.'
except jwt.InvalidTokenError:
return 'Invalid token. Please log in again.'
示例8: login_required
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignatureError [as 别名]
def login_required(method):
@functools.wraps(method)
def wrapper(self):
header = request.headers.get('Authorization')
_, token = header.split()
try:
decoded = jwt.decode(token, app.config['KEY'], algorithms='HS256')
except jwt.DecodeError:
abort(400, message='Token is not valid.')
except jwt.ExpiredSignatureError:
abort(400, message='Token is expired.')
email = decoded['email']
if db.users.find({'email': email}).count() == 0:
abort(400, message='User is not found.')
user = db.users.find_one({'email': email})
return method(self, user)
return wrapper
示例9: _auth_with_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignatureError [as 别名]
def _auth_with_token():
auth_headers = request.headers.get('Access-Token', '').strip()
if not auth_headers:
return False
try:
token = auth_headers
data = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
user = User.query.filter_by(email=data['sub']).first()
if not user:
return False
login_user(user)
g.user = user
return True
except jwt.ExpiredSignatureError:
return False
except (jwt.InvalidTokenError, Exception):
return False
示例10: _set_error_handler_callbacks
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignatureError [as 别名]
def _set_error_handler_callbacks(self, app):
"""
Sets the error handler callbacks used by this extension
"""
@app.errorhandler(NoAuthorizationError)
def handle_no_auth_error(e):
return self._unauthorized_callback(str(e))
@app.errorhandler(InvalidHeaderError)
def handle_invalid_header_error(e):
return self._invalid_token_callback(str(e))
@app.errorhandler(jwt.ExpiredSignatureError)
def handle_expired_error(e):
return self._expired_token_callback()
@app.errorhandler(jwt.InvalidTokenError)
def handle_invalid_token_error(e):
return self._invalid_token_callback(str(e))
示例11: authenticate
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignatureError [as 别名]
def authenticate(cls, jwt_token):
"""
Validates if JWT Token still stands True.
:param jwt_token: JWT Token issued by generate_token method
:return: A dict containing status and payload on success
"""
if jwt_token:
try:
payload = jwt.decode(jwt_token, cls.app_secret)
except (jwt.DecodeError, jwt.ExpiredSignatureError) as e:
cls.token_authenticator_logger.exception(
'[JWT Manager]: Authentication failed due to : {}'.format(str(e)))
return {
'status': False,
'message': 'Token invalid {}'.format(str(e)),
'encode_value': None
}
cls.token_authenticator_logger.info('[JWT Manager]: Authentication succeded.')
return {
'status': True,
'message': 'Token valid',
'encode_value': payload['encode_value']
}
示例12: test_decode_jwt_expired
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignatureError [as 别名]
def test_decode_jwt_expired(self):
payload = self._get_payload()
now = datetime.utcnow()
payload['exp'] = now - timedelta(seconds=1)
payload['iat'] = now
jwt_value = utils.encode_jwt(payload)
self.assertRaises(jwt.ExpiredSignatureError, utils.decode_jwt,
jwt_value)
示例13: validate_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignatureError [as 别名]
def validate_token(self, data):
"""Verify token is valid."""
try:
payload = jwt.decode(data, settings.SECRET_KEY, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
raise serializers.ValidationError('Verification link has expired.')
except jwt.PyJWTError:
raise serializers.ValidationError('Invalid token')
if payload['type'] != 'email_confirmation':
raise serializers.ValidationError('Invalid token')
self.context['payload'] = payload
return data
示例14: __check_auth
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignatureError [as 别名]
def __check_auth(self, view):
headers = {x[0]: x[1] for x in request.headers}
if 'Authorization' in headers:
try:
token = jwt.decode(
headers['Authorization'],
get_jwt_key_data()
)
if token['auth_system'] != current_app.active_auth_system.name:
self.log.error('Token is from another auth_system ({}) than the current one ({})'.format(
token['auth_system'],
current_app.active_auth_system.name
))
return view.make_unauth_response()
if has_access(session['user'], self.role):
return
self.log.error('User {} attempted to access page {} without permissions'.format(
session['user'].username,
request.path
))
return view.make_unauth_response()
except (jwt.DecodeError, jwt.ExpiredSignatureError) as ex:
session.clear()
view.log.info('Failed to decode signature or it had expired: {0}'.format(ex))
return view.make_unauth_response()
session.clear()
view.log.info('Failed to detect Authorization header')
return view.make_unauth_response()
示例15: decode_auth_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignatureError [as 别名]
def decode_auth_token(auth_token):
"""Decodes the auth token - :param auth_token: - :return: integer|string"""
try:
payload = jwt.decode(
auth_token, current_app.config.get('SECRET_KEY'))
return payload['sub']
except jwt.ExpiredSignatureError:
return 'Signature expired. Please log in again.'
except jwt.InvalidTokenError:
return 'Invalid token. Please log in again.'