本文整理汇总了Python中jwt.ExpiredSignature方法的典型用法代码示例。如果您正苦于以下问题:Python jwt.ExpiredSignature方法的具体用法?Python jwt.ExpiredSignature怎么用?Python jwt.ExpiredSignature使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jwt
的用法示例。
在下文中一共展示了jwt.ExpiredSignature方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: process_request
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignature [as 别名]
def process_request(self, request):
if request.META.get('HTTP_AUTHORIZATION'):
token = (request.META.get('HTTP_AUTHORIZATION').split(' '))[1]
try:
payload = jwt_decode_handler(token)
user_id = jwt_get_user_id_from_payload_handler(payload)
if not user_id:
return JsonResponse({"message": "用户不存在!" , "errorCode": 2, "data": {}})
now_user = User.objects.values('id', 'is_freeze').filter(id=user_id).first()
if not now_user:
return JsonResponse({"message": "用户不存在!" , "errorCode": 2, "data": {}})
if now_user.get('is_freeze'):
return JsonResponse({"message": "账户被冻结!", "errorCode": 2, "data": {}})
except jwt.ExpiredSignature:
return JsonResponse({"message": 'Token过期' , "errorCode": 2, "data": {}})
except jwt.DecodeError:
return JsonResponse({"message": 'Token不合法' , "errorCode": 2, "data": {}})
except jwt.InvalidTokenError as e:
return JsonResponse({"message": "出现了无法预料的view视图错误:%s" % e, "errorCode": 1, "data": {}})
示例2: authenticate
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignature [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 = jwt_decode_handler(jwt_value)
except jwt.ExpiredSignature:
msg = 'Token过期'
raise exceptions.AuthenticationFailed({"message": msg,"errorCode":1,"data":{}})
except jwt.DecodeError:
msg = 'Token不合法'
raise exceptions.AuthenticationFailed({"message": msg,"errorCode":1,"data":{}})
except jwt.InvalidTokenError:
raise exceptions.AuthenticationFailed()
user = self.authenticate_credentials(payload)
return user, jwt_value
示例3: login_req
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignature [as 别名]
def login_req(f):
@wraps(f)
def decorated_func(*args, **kwargs):
if not request.headers.get('Authorization'):
return jsonify(message='Please login'), 401
try:
payload = _parse_token_from_header(request)
g.user_id = payload['sub']
return f(*args, **kwargs)
except DecodeError:
return jsonify(message='Your session is invalid'), 401
except ExpiredSignature:
return jsonify(message='\
Your session has expired. Please login again.'), 401
return decorated_func
示例4: authenticate
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignature [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 = jwt_decode_handler(jwt_value)
except jwt.ExpiredSignature:
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()
user = self.authenticate_credentials(payload)
return (user, payload)
示例5: validate
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignature [as 别名]
def validate(self, token):
public_key = self._get_public_key(token)
if not public_key:
raise TokenError("No key found for this token")
try:
jwt_data = jwt.decode(
token,
public_key,
audience=self.audience,
issuer=self.pool_url,
algorithms=["RS256"],
)
except (jwt.InvalidTokenError, jwt.ExpiredSignature, jwt.DecodeError) as exc:
raise TokenError(str(exc))
return jwt_data
示例6: authenticated
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignature [as 别名]
def authenticated(func):
"""Handle tokens from requests."""
@wraps(func)
def wrapper(*args, **kwargs):
"""Verify the requires of token."""
try:
content = request.headers.get("Authorization")
if content is None:
raise AttributeError
token = content.split("Bearer ")[1]
jwt.decode(token, key=Auth.get_jwt_secret())
except (
AttributeError,
IndexError,
jwt.ExpiredSignature,
jwt.exceptions.DecodeError,
) as exc:
msg = f"Token not sent or expired: {exc}"
return jsonify({"error": msg}), HTTPStatus.UNAUTHORIZED.value
return func(*args, **kwargs)
return wrapper
示例7: user_data
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignature [as 别名]
def user_data(self, access_token, *args, **kwargs):
response = kwargs.get('response')
id_token = response.get('id_token')
# decode the JWT header as JSON dict
jwt_header = json.loads(
base64.b64decode(id_token.split('.', 1)[0]).decode()
)
# get key id and algorithm
key_id = jwt_header['kid']
algorithm = jwt_header['alg']
try:
# retrieve certificate for key_id
certificate = self.get_certificate(key_id)
return jwt_decode(
id_token,
key=certificate.public_key(),
algorithms=algorithm,
audience=self.setting('SOCIAL_AUTH_AZUREAD_OAUTH2_KEY')
)
except (DecodeError, ExpiredSignature) as error:
raise AuthTokenError(self, error)
示例8: user_data
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignature [as 别名]
def user_data(self, access_token, *args, **kwargs):
response = kwargs.get('response')
id_token = response.get('id_token')
if six.PY2:
# str() to fix a bug in Python's base64
# https://stackoverflow.com/a/2230623/161278
id_token = str(id_token)
jwt_header_json = base64url_decode(id_token.split('.')[0])
jwt_header = json.loads(jwt_header_json.decode('ascii'))
# `kid` is short for key id
key = self.get_public_key(jwt_header['kid'])
try:
return jwt_decode(
id_token,
key=key,
algorithms=jwt_header['alg'],
audience=self.setting('KEY'),
leeway=self.setting('JWT_LEEWAY', default=0),
)
except (DecodeError, ExpiredSignature) as error:
raise AuthTokenError(self, error)
示例9: _decode_header
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignature [as 别名]
def _decode_header(auth_header, client_id, client_secret):
"""
Takes the header and tries to return an active token and decoded
payload.
:param auth_header:
:param client_id:
:param client_secret:
:return: (token, profile)
"""
try:
token = auth_header.split()[1]
payload = jwt.decode(
token,
client_secret,
audience=client_id)
except jwt.ExpiredSignature:
raise exceptions.NotAuthorizedException(
'Token has expired, please log in again.')
# is valid client
except jwt.InvalidAudienceError:
message = 'Incorrect audience, expected: {}'.format(
client_id)
raise exceptions.NotAuthorizedException(message)
# is valid token
except jwt.DecodeError:
raise exceptions.NotAuthorizedException(
'Token signature could not be validated.')
except Exception as e:
raise exceptions.NotAuthorizedException(
'Token signature was malformed. {}'.format(e.message))
return token, payload
示例10: validate_csrf_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignature [as 别名]
def validate_csrf_token(self, request, token):
bad_token = request.config['CSRF_BAD_TOKEN_MESSAGE']
expired_token = request.config['CSRF_EXPIRED_TOKEN_MESSAGE']
if not token:
raise PermissionDenied(bad_token)
try:
jwt.decode(token, request.cache.session.id)
except jwt.ExpiredSignature:
raise PermissionDenied(expired_token)
except Exception:
raise PermissionDenied(bad_token)
示例11: get_payload
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignature [as 别名]
def get_payload(token, context=None):
try:
payload = jwt_settings.JWT_DECODE_HANDLER(token, context)
except jwt.ExpiredSignature:
raise exceptions.JSONWebTokenExpired()
except jwt.DecodeError:
raise exceptions.JSONWebTokenError(_('Error decoding signature'))
except jwt.InvalidTokenError:
raise exceptions.JSONWebTokenError(_('Invalid token'))
return payload
示例12: _check_payload
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignature [as 别名]
def _check_payload(self, token):
# Check payload valid (based off of JSONWebTokenAuthentication,
# may want to refactor)
try:
payload = jwt_decode_handler(token)
except jwt.ExpiredSignature:
msg = _('Signature has expired.')
raise serializers.ValidationError(msg)
except jwt.DecodeError:
msg = _('Error decoding signature.')
raise serializers.ValidationError(msg)
return payload
示例13: get_profile
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignature [as 别名]
def get_profile(self, token):
"""Gets the user from credentials object. None if no credentials.
Can raise jwt.ExpiredSignature and jwt.DecodeError"""
profile = jwt.decode(token, self.secret)
return profile
示例14: get_user
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignature [as 别名]
def get_user(self, token):
"""Gets the user from credentials object. None if no credentials.
Can raise jwt.ExpiredSignature and jwt.DecodeError"""
profile = self.get_profile(token)
if not profile:
return None
username = profile.get("user", None)
user = self.server_store.read_user(username)
# Timestamp must match with the stored in user, if not,
# this token is not valid (password has been changed)
password_timestamp = profile["password_timestamp"]
if password_timestamp != user.password_timestamp:
logger.debug("Timestamp doesn't match!")
raise jwt.DecodeError("Timestamp doesn't match!")
return username
示例15: validate_access_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import ExpiredSignature [as 别名]
def validate_access_token(self, access_token):
for idx, key in enumerate(provider_config.signing_keys):
try:
# Explicitly define the verification option.
# The list below is the default the jwt module uses.
# Explicit is better then implicit and it protects against
# changes in the defaults the jwt module uses.
options = {
'verify_signature': True,
'verify_exp': True,
'verify_nbf': True,
'verify_iat': True,
'verify_aud': True,
'verify_iss': True,
'require_exp': False,
'require_iat': False,
'require_nbf': False
}
# Validate token and return claims
return jwt.decode(
access_token,
key=key,
algorithms=['RS256', 'RS384', 'RS512'],
verify=True,
audience=settings.AUDIENCE,
issuer=provider_config.issuer,
options=options,
)
except jwt.ExpiredSignature as error:
logger.info("Signature has expired: %s", error)
raise PermissionDenied
except jwt.DecodeError as error:
# If it's not the last certificate in the list, skip to the next one
if idx < len(provider_config.signing_keys) - 1:
continue
else:
logger.info('Error decoding signature: %s', error)
raise PermissionDenied
except jwt.InvalidTokenError as error:
logger.info(str(error))
raise PermissionDenied