本文整理汇总了Python中jwt.DecodeError方法的典型用法代码示例。如果您正苦于以下问题:Python jwt.DecodeError方法的具体用法?Python jwt.DecodeError怎么用?Python jwt.DecodeError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jwt
的用法示例。
在下文中一共展示了jwt.DecodeError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: authenticate
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import DecodeError [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)
示例2: process_request
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import DecodeError [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": {}})
示例3: authenticate
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import DecodeError [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
示例4: fetch_token_header
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import DecodeError [as 别名]
def fetch_token_header(token):
"""
Fetch the header out of the JWT token.
:param token:
:return: :raise jwt.DecodeError:
"""
token = token.encode("utf-8")
try:
signing_input, crypto_segment = token.rsplit(b".", 1)
header_segment, payload_segment = signing_input.split(b".", 1)
except ValueError:
raise jwt.DecodeError("Not enough segments")
try:
return json.loads(jwt.utils.base64url_decode(header_segment).decode("utf-8"))
except TypeError as e:
current_app.logger.exception(e)
raise jwt.DecodeError("Invalid header padding")
示例5: login_req
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import DecodeError [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
示例6: authenticate
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import DecodeError [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)
示例7: _get_public_key
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import DecodeError [as 别名]
def _get_public_key(self, token):
try:
headers = jwt.get_unverified_header(token)
except jwt.DecodeError as exc:
raise TokenError(str(exc))
if getattr(settings, "COGNITO_PUBLIC_KEYS_CACHING_ENABLED", False):
cache_key = "django_cognito_jwt:%s" % headers["kid"]
jwk_data = cache.get(cache_key)
if not jwk_data:
jwk_data = self._json_web_keys.get(headers["kid"])
timeout = getattr(settings, "COGNITO_PUBLIC_KEYS_CACHING_TIMEOUT", 300)
cache.set(cache_key, jwk_data, timeout=timeout)
else:
jwk_data = self._json_web_keys.get(headers["kid"])
if jwk_data:
return RSAAlgorithm.from_jwk(jwk_data)
示例8: validate
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import DecodeError [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
示例9: update_token
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import DecodeError [as 别名]
def update_token(self, token: str) -> None:
"""
Replace this connection's API token with a new one.
Parameters
----------
token : str
JSON Web Token for this API server
"""
try:
self.user = jwt.decode(token, verify=False)["identity"]
except jwt.DecodeError:
raise FlowclientConnectionError(f"Unable to decode token: '{token}'")
except KeyError:
raise FlowclientConnectionError(f"Token does not contain user identity.")
self.token = token
self.session.headers["Authorization"] = f"Bearer {self.token}"
示例10: get_certificate
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import DecodeError [as 别名]
def get_certificate(self, kid):
# retrieve keys from jwks_url
resp = self.request(self.jwks_url(), method='GET')
resp.raise_for_status()
# find the proper key for the kid
for key in resp.json()['keys']:
if key['kid'] == kid:
x5c = key['x5c'][0]
break
else:
raise DecodeError('Cannot find kid={}'.format(kid))
certificate = '-----BEGIN CERTIFICATE-----\n' \
'{}\n' \
'-----END CERTIFICATE-----'.format(x5c)
return load_pem_x509_certificate(certificate.encode(),
default_backend())
示例11: user_data
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import DecodeError [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)
示例12: user_data
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import DecodeError [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)
示例13: login_required
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import DecodeError [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
示例14: verify
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import DecodeError [as 别名]
def verify(self, token, verifying_key):
# grab the token parts
token_parts = self._unpack(token)
header, payload, raw_signature, signing_input = token_parts
# load the verifying key
verifying_key = load_verifying_key(verifying_key, self.crypto_backend)
# convert the raw_signature to DER format
der_signature = raw_to_der_signature(
raw_signature, verifying_key.curve)
# initialize the verifier
verifier = self._get_verifier(verifying_key, der_signature)
verifier.update(signing_input)
# check to see whether the signature is valid
try:
verifier.verify()
except InvalidSignature:
# raise DecodeError('Signature verification failed')
return False
return True
示例15: authenticate
# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import DecodeError [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']
}