Python jwt.InvalidTokenError() Examples
The following are 30
code examples of jwt.InvalidTokenError().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
jwt
, or try the search function
.
Example #1
Source File: validator.py From django-cognito-jwt with MIT License | 9 votes |
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
Example #2
Source File: auth.py From zulip with Apache License 2.0 | 6 votes |
def log_into_subdomain(request: HttpRequest, token: str) -> HttpResponse: """Given a valid authentication token (generated by redirect_and_log_into_subdomain called on auth.zulip.example.com), call login_or_register_remote_user, passing all the authentication result data that has been stored in redis, associated with this token. """ if not has_api_key_format(token): # The tokens are intended to have the same format as API keys. logging.warning("log_into_subdomain: Malformed token given: %s", token) return HttpResponse(status=400) try: result = ExternalAuthResult(login_token=token) except ExternalAuthResult.InvalidTokenError: logging.warning("log_into_subdomain: Invalid token given: %s", token) return render(request, 'zerver/log_into_subdomain_token_invalid.html', status=400) subdomain = get_subdomain(request) if result.data_dict['subdomain'] != subdomain: raise JsonableError(_("Invalid subdomain")) return login_or_register_remote_user(request, result)
Example #3
Source File: test_handlers.py From ecommerce with GNU Affero General Public License v3.0 | 6 votes |
def test_decode_error_invalid_token(self, mock_logger): """ Invalid token will fail both multiple-issuers and the fallback of edx-drf-extensions jwt_decode_handler. """ # Update the payload to ensure a validation error payload = generate_jwt_payload(self.user, issuer_name='test-issuer-2') payload['exp'] = 0 token = generate_jwt_token(payload, 'test-secret-key-2') with self.assertRaises(jwt.InvalidTokenError): jwt_decode_handler(token) mock_logger.exception.assert_called_with('Custom config JWT decode failed!') mock_logger.info.assert_has_calls(calls=[ mock.call('Failed to use ecommerce multiple issuer jwt_decode_handler.', exc_info=True), mock.call('Failed to use edx-drf-extensions jwt_decode_handler.', exc_info=True), ])
Example #4
Source File: blacklist.py From fence with Apache License 2.0 | 6 votes |
def is_token_blacklisted(encoded_token, public_key=None): """ Decode an encoded token and check if it is blacklisted. Args: encoded_token (str): JWT to check public key (Optional[str]): key to decode JWT with Return: bool: whether JWT is blacklisted """ public_key = public_key or keys.default_public_key() try: token = jwt.decode( encoded_token, public_key, algorithm="RS256", audience="openid" ) except jwt.exceptions.InvalidTokenError as e: raise JWTError("could not decode token to check blacklisting: {}".format(e)) return is_blacklisted(token["jti"])
Example #5
Source File: backends.py From falcon-auth with MIT License | 6 votes |
def _decode_jwt_token(self, req): # Decodes the jwt token into a payload auth_header = req.get_header('Authorization') token = self.parse_auth_token_from_request(auth_header=auth_header) options = dict(('verify_' + claim, True) for claim in self.verify_claims) options.update( dict(('require_' + claim, True) for claim in self.required_claims) ) try: payload = jwt.decode(jwt=token, key=self.secret_key, options=options, algorithms=[self.algorithm], issuer=self.issuer, audience=self.audience, leeway=self.leeway) except jwt.InvalidTokenError as ex: raise falcon.HTTPUnauthorized( description=str(ex)) return payload
Example #6
Source File: models.py From flask-jwt-auth with MIT License | 6 votes |
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.'
Example #7
Source File: policy.py From muesli with GNU General Public License v3.0 | 6 votes |
def get_claims(self, request): if self.http_header == 'Authorization': try: if request.authorization is None: return {} except ValueError: # Invalid Authorization header return {} (auth_type, token) = request.authorization if auth_type != self.auth_type: return {} else: token = request.headers.get(self.http_header) if not token: return {} try: claims = jwt.decode(token, self.public_key, algorithms=[self.algorithm], leeway=self.leeway, audience=self.audience) if request.db.query(models.BearerToken).get(claims["jti"]).revoked: return {} else: return claims except jwt.InvalidTokenError as e: log.warning('Invalid JWT token from %s: %s', request.remote_addr, e) return {}
Example #8
Source File: authentication.py From django-rest-framework-jwt with MIT License | 6 votes |
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)
Example #9
Source File: twofactor_auth.py From balena-sdk-python with Apache License 2.0 | 6 votes |
def is_enabled(self): """ Check if two-factor authentication is enabled. Returns: bool: True if enabled. Otherwise False. Examples: >>> balena.twofactor_auth.is_enabled() False """ try: token = self.settings.get(TOKEN_KEY) token_data = jwt.decode(token, verify=False) if 'twoFactorRequired' in token_data: return True return False except jwt.InvalidTokenError: # in case it's not Auth token raise exceptions.UnsupportedFeature()
Example #10
Source File: jwtAuth.py From django-RESTfulAPI with MIT License | 6 votes |
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
Example #11
Source File: BaseMiddleWare.py From django-RESTfulAPI with MIT License | 6 votes |
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": {}})
Example #12
Source File: auth.py From cmdb with GNU General Public License v2.0 | 6 votes |
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
Example #13
Source File: __init__.py From flask-jwt with MIT License | 6 votes |
def _jwt_required(realm): """Does the actual work of verifying the JWT data in the current request. This is done automatically for you by `jwt_required()` but you could call it manually. Doing so would be useful in the context of optional JWT access in your APIs. :param realm: an optional realm """ token = _jwt.request_callback() if token is None: raise JWTError('Authorization Required', 'Request does not contain an access token', headers={'WWW-Authenticate': 'JWT realm="%s"' % realm}) try: payload = _jwt.jwt_decode_callback(token) except jwt.InvalidTokenError as e: raise JWTError('Invalid token', str(e)) _request_ctx_stack.top.current_identity = identity = _jwt.identity_callback(payload) if identity is None: raise JWTError('Invalid JWT', 'User does not exist')
Example #14
Source File: jwt_manager.py From flask-jwt-simple with MIT License | 6 votes |
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))
Example #15
Source File: jwt_token.py From ops_sdk with GNU General Public License v3.0 | 6 votes |
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')
Example #16
Source File: auth.py From flask-restful-example with MIT License | 6 votes |
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
Example #17
Source File: token.py From apistar-jwt with MIT License | 6 votes |
def decode(self, token) -> Optional[JWTUser]: try: payload = PyJWT.decode(token, self.secret, algorithms=self.algorithms, **self.options) if payload == {}: return None except PyJWT.MissingRequiredClaimError as exc: log.warning('JWT Missing claim: %s', exc.claim) return None except PyJWT.InvalidTokenError as exc: log.exception('JWT Invalid Token: %s', exc.__class__.__name__) return None except Exception as exc: log.exception('JWT Exception: %s', exc.__class__.__name__) return None _id = payload.get(self.ID) username = payload.get(self.USERNAME) return JWTUser(id=_id, username=username, token=payload)
Example #18
Source File: user.py From SempoBlockchain with GNU General Public License v3.0 | 6 votes |
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)
Example #19
Source File: auth.py From selene-backend with GNU Affero General Public License v3.0 | 6 votes |
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
Example #20
Source File: authentication.py From django-oauth-toolkit-jwt with MIT License | 6 votes |
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)
Example #21
Source File: jwt.py From flask-resty with MIT License | 5 votes |
def get_jwk_for_jwt(self, unverified_header): try: token_kid = unverified_header["kid"] except KeyError as e: raise InvalidTokenError( "Key ID header parameter is missing" ) from e for jwk in self.jwk_set["keys"]: if jwk["kid"] == token_kid: return jwk raise InvalidTokenError("no key found")
Example #22
Source File: jwt.py From flask-resty with MIT License | 5 votes |
def get_credentials_from_token(self, token): try: payload = self.decode_token(token) except InvalidTokenError as e: raise ApiError(401, {"code": "invalid_token"}) from e return payload
Example #23
Source File: token.py From asymmetric-jwt-auth with ISC License | 5 votes |
def verify(token, public_key, validate_nonce=None, algorithms=[DEFAULT_ALGORITHM]): """ Verify the validity of the given JWT using the given public key. :param token: JWM claim :param public_key: Public key to use when verifying the claim's signature. :param validate_nonce: Callable to use to validate the claim's nonce. :param algorithms: Allowable signing algorithms. Defaults to ['RS512']. :return: False if the token is determined to be invalid or a dictionary of the token data if it is valid. """ try: token_data = jwt.decode(token, public_key, algorithms=algorithms) except jwt.InvalidTokenError: logger.debug('JWT failed verification') return False claimed_username = token_data.get('username') claimed_time = token_data.get('time', 0) claimed_nonce = token_data.get('nonce') # Ensure time is within acceptable bounds current_time = time.time() min_time, max_time = (current_time - TIMESTAMP_TOLERANCE, current_time + TIMESTAMP_TOLERANCE) if claimed_time < min_time or claimed_time > max_time: logger.debug('Claimed time is outside of allowable tolerances') return False # Ensure nonce is unique if validate_nonce: if not validate_nonce(claimed_username, claimed_time, claimed_nonce): logger.debug('Claimed nonce failed to validate') return False else: logger.warning('validate_nonce function was not supplied!') # If we've gotten this far, the token is valid return token_data
Example #24
Source File: handlers.py From ecommerce with GNU Affero General Public License v3.0 | 5 votes |
def jwt_decode_handler(token): """ Attempt to decode the given token with each of the configured JWT issuers. Args: token (str): The JWT to decode. Returns: dict: The JWT's payload. Raises: InvalidTokenError: If the token is invalid, or if none of the configured issuer/secret-key combos can properly decode the token. """ # First, try ecommerce decoder that handles multiple issuers. # See ARCH-276 for details of removing additional issuers and retiring this # custom jwt_decode_handler. try: jwt_payload = _ecommerce_jwt_decode_handler_multiple_issuers(token) monitoring_utils.set_custom_metric(JWT_DECODE_HANDLER_METRIC_KEY, 'ecommerce-multiple-issuers') return jwt_payload except Exception: # pylint: disable=broad-except if waffle.switch_is_active('jwt_decode_handler.log_exception.ecommerce-multiple-issuers'): logger.info('Failed to use ecommerce multiple issuer jwt_decode_handler.', exc_info=True) # Next, try jwt_decode_handler from edx_drf_extensions # Note: this jwt_decode_handler can handle asymmetric keys, but only a # single issuer. Therefore, the LMS must be the first configured issuer. try: jwt_payload = edx_drf_extensions_jwt_decode_handler(token) monitoring_utils.set_custom_metric(JWT_DECODE_HANDLER_METRIC_KEY, 'edx-drf-extensions') return jwt_payload except Exception: # pylint: disable=broad-except # continue and try again if waffle.switch_is_active('jwt_decode_handler.log_exception.edx-drf-extensions'): logger.info('Failed to use edx-drf-extensions jwt_decode_handler.', exc_info=True) raise
Example #25
Source File: models.py From flask-rest-api with MIT License | 5 votes |
def decode_token(token): """Decode the access token from the Authorization header.""" try: payload = jwt.decode(token, current_app.config.get('SECRET')) return payload['sub'] except jwt.ExpiredSignatureError: return "Expired token. Please log in to get a new token" except jwt.InvalidTokenError: return "Invalid token. Please register or login"
Example #26
Source File: test_handlers.py From ecommerce with GNU Affero General Public License v3.0 | 5 votes |
def test_decode_success_edx_drf_extensions(self, mock_multiple_issuer_decoder, mock_set_custom_metric): """ Should pass using the edx-drf-extensions jwt_decode_handler. This would happen if ``_ecommerce_jwt_decode_handler_multiple_issuers`` should fail (e.g. using asymmetric tokens). """ mock_multiple_issuer_decoder.side_effect = jwt.InvalidTokenError() first_issuer = settings.JWT_AUTH['JWT_ISSUERS'][0] payload = generate_jwt_payload(self.user, issuer_name=first_issuer['ISSUER']) token = generate_jwt_token(payload, first_issuer['SECRET_KEY']) self.assertDictContainsSubset(payload, jwt_decode_handler(token)) mock_set_custom_metric.assert_called_with('ecom_jwt_decode_handler', 'edx-drf-extensions')
Example #27
Source File: util.py From havcs with Apache License 2.0 | 5 votes |
def async_update_token_expiration(access_token, hass, expiration): try: unverif_claims = jwt.decode(access_token, verify=False) refresh_token = await hass.auth.async_get_refresh_token(cast(str, unverif_claims.get('iss'))) for user in hass.auth._store._users.values(): if refresh_token.id in user.refresh_tokens and refresh_token.access_token_expiration != expiration: _LOGGER.debug("[util] set new access token expiration for refresh_token[%s]", refresh_token.id) refresh_token.access_token_expiration = expiration user.refresh_tokens[refresh_token.id] = refresh_token hass.auth._store._async_schedule_save() break except jwt.InvalidTokenError: _LOGGER.debug("[util] access_token[%s] is invalid, try another reauthorization on website", access_token)
Example #28
Source File: backend.py From django-auth-adfs with BSD 2-Clause "Simplified" License | 5 votes |
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
Example #29
Source File: transaction_serializers.py From silver with Apache License 2.0 | 5 votes |
def get_object(self, view_name, view_args, view_kwargs): try: transaction_uuid = jwt.decode(view_kwargs['token'], settings.PAYMENT_METHOD_SECRET)['transaction'] return self.queryset.get(uuid=transaction_uuid) except (jwt.ExpiredSignatureError, jwt.DecodeError, jwt.InvalidTokenError): return None
Example #30
Source File: models.py From my-dev-space with MIT License | 5 votes |
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."