Python jwt.ExpiredSignatureError() Examples

The following are 30 code examples of jwt.ExpiredSignatureError(). 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: jwt_manager.py    From PROTON with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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']
            } 
Example #2
Source File: jwt_token.py    From ops_sdk with GNU General Public License v3.0 6 votes vote down vote up
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 #3
Source File: authentication.py    From django-oauth-toolkit-jwt with MIT License 6 votes vote down vote up
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 #4
Source File: models.py    From flask-jwt-auth with MIT License 6 votes vote down vote up
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 #5
Source File: decorators.py    From silver with Apache License 2.0 6 votes vote down vote up
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 
Example #6
Source File: api.py    From flask-restful-authentication with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #7
Source File: auth.py    From cmdb with GNU General Public License v2.0 6 votes vote down vote up
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 #8
Source File: auth.py    From flask-restful-example with MIT License 6 votes vote down vote up
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 #9
Source File: jwt_manager.py    From flask-jwt-simple with MIT License 6 votes vote down vote up
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 #10
Source File: user.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
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 #11
Source File: auth.py    From selene-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #12
Source File: webauth.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def check_jwt_token():
    jwt_cookie = str(JWT_COOKIE_NAME + plexpy.CONFIG.PMS_UUID)
    jwt_token = cherrypy.request.cookie.get(jwt_cookie)

    if jwt_token:
        try:
            payload = jwt.decode(
                jwt_token.value, plexpy.CONFIG.JWT_SECRET, leeway=timedelta(seconds=10), algorithms=[JWT_ALGORITHM]
            )
        except (jwt.DecodeError, jwt.ExpiredSignatureError):
            return None

        return payload 
Example #13
Source File: api.py    From flask-restful-authentication with GNU General Public License v3.0 5 votes vote down vote up
def put(self):
        activation_code = request.json['activation_code']
        try:
            decoded = jwt.decode(activation_code, app.config['KEY'], algorithms='HS256')
        except jwt.DecodeError:
            abort(400, message='Activation code is not valid.')
        except jwt.ExpiredSignatureError:
            abort(400, message='Activation code is expired.')
        email = decoded['email']
        db.users.update({'email': email}, {'$set': {'active': True}})
        return {'email': email} 
Example #14
Source File: models.py    From my-dev-space with MIT License 5 votes vote down vote up
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." 
Example #15
Source File: auth.py    From bottle-jwt with GNU General Public License v3.0 5 votes vote down vote up
def validate_token(self, token=''):
        """Validate JWT token.

        Args:
            token (str): A Json Web token string.

        Returns:
            The decrypted token data (dict)

        Raises:
            JWTProviderError, if no token is provided, or if it is expired.
        """
        if not token:
            logger.debug("Forbidden access")
            raise JWTForbiddenError('Cannot access this resource!')

        try:
            decoded = jwt.decode(
                token.split(" ", 1).pop(),
                self.secret,
                algorithms=self.algorithm
            )

            logger.debug("Token validation passed: {}".format(token))

            user_uid = decoded.get('sub')

            if not user_uid:  # pragma: no cover
                raise JWTUnauthorizedError('Invalid User token')

            user = self.backend.get_user(json.loads(base64.b64decode(user_uid).decode('utf-8')))

            if user:
                return user

            raise JWTUnauthorizedError('Invalid User token')

        except (jwt.DecodeError, jwt.ExpiredSignatureError) as e:
            logger.debug("{}: {}".format(e.args[0], token))
            raise JWTUnauthorizedError("Invalid auth token provided.") 
Example #16
Source File: transaction_serializers.py    From silver with Apache License 2.0 5 votes vote down vote up
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 #17
Source File: models.py    From flask-rest-api with MIT License 5 votes vote down vote up
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 #18
Source File: claims_time.py    From Learning-Path-Learn-Web-Development-with-Python with MIT License 5 votes vote down vote up
def decode(token, secret):
    print(datetime.utcnow().time().isoformat())
    try:
        print(jwt.decode(token, secret))
    except (
        jwt.ImmatureSignatureError, jwt.ExpiredSignatureError
    ) as err:
        print(err)
        print(type(err)) 
Example #19
Source File: user.py    From flask-base-api with MIT License 5 votes vote down vote up
def decode_email_token(email_token: str) -> int:
        """Decodes the auth token - :param auth_token: - :return: integer|string"""
        try:
            payload = jwt.decode(email_token, current_app.config.get('SECRET_KEY'))
            return payload['sub']
        except jwt.ExpiredSignatureError:
            raise BusinessException(message='Email recovery token expired. Please try again.')
        except jwt.InvalidTokenError:
            raise BusinessException(message='Invalid email verification token. Please try again.') 
Example #20
Source File: auth.py    From stethoscope with Apache License 2.0 5 votes vote down vote up
def decode_token(self, token):
    try:
      decoded = jwt.decode(token, self.config['JWT_SECRET_KEY'],
          algorithms=[self.config['JWT_ALGORITHM']], leeway=self.config.get('JWT_LEEWAY', 0))
    except jwt.ExpiredSignatureError:
      raise werkzeug.exceptions.Unauthorized("JWT Error: Token is expired.")
    except jwt.DecodeError:
      raise werkzeug.exceptions.Unauthorized("JWT Error: Token could not be decoded.")
    except jwt.InvalidTokenError:
      raise werkzeug.exceptions.Unauthorized("JWT Error: Token is invalid.")
    return decoded 
Example #21
Source File: user.py    From flask-base-api with MIT License 5 votes vote down vote up
def decode_password_token(pass_token: str) -> int:
        """Decodes the auth token - :param auth_token: - :return: integer|string"""
        try:
            payload = jwt.decode(pass_token, current_app.config.get('SECRET_KEY'))
            return payload['sub']
        except jwt.ExpiredSignatureError:
            raise BusinessException(message='Password recovery token expired. Please try again.')
        except jwt.InvalidTokenError:
            raise BusinessException(message='Invalid password recovery token. Please try again.') 
Example #22
Source File: user.py    From flask-base-api with MIT License 5 votes vote down vote up
def decode_auth_token(auth_token: str) -> int:
        """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:
            raise UnauthorizedException(message='Signature expired. Please log in again.')
        except jwt.InvalidTokenError:
            raise UnauthorizedException(message='Invalid token. Please log in again.') 
Example #23
Source File: views.py    From lemur with Apache License 2.0 5 votes vote down vote up
def validate_id_token(id_token, client_id, jwks_url):
    """
    Ensures that the token we receive is valid.

    :param id_token:
    :param client_id:
    :param jwks_url:
    :return:
    """
    # fetch token public key
    header_data = fetch_token_header(id_token)

    # retrieve the key material as specified by the token header
    r = requests.get(jwks_url)
    for key in r.json()["keys"]:
        if key["kid"] == header_data["kid"]:
            secret = get_rsa_public_key(key["n"], key["e"])
            algo = header_data["alg"]
            break
    else:
        return dict(message="Key not found"), 401

    # validate your token based on the key it was signed with
    try:
        jwt.decode(
            id_token, secret.decode("utf-8"), algorithms=[algo], audience=client_id
        )
    except jwt.DecodeError:
        return dict(message="Token is invalid"), 401
    except jwt.ExpiredSignatureError:
        return dict(message="Token has expired"), 401
    except jwt.InvalidTokenError:
        return dict(message="Token is invalid"), 401 
Example #24
Source File: Scrummage.py    From Scrummage with GNU General Public License v3.0 5 votes vote down vote up
def API_verification(auth_token):

        try:
            Decoded_Token = jwt.decode(auth_token, API_Secret, algorithm='HS256')
            User_ID = int(Decoded_Token['id'])
            Cursor.execute('SELECT * FROM users WHERE user_id = %s', (User_ID,))
            User_Details = Cursor.fetchone()

            if auth_token == User_Details[5]:

                if not User_Details[3]:
                    return {"Token": True, "Admin": User_Details[4], "Username": User_Details[1], "Message": "Token verification successful."}

                else:
                    return {"Token": False, "Admin": False, "Message": "Token blocked."}

            else:
                return {"Token": False, "Admin": False, "Message": "Invalid token."}

        except jwt.ExpiredSignatureError:
            return {"Token": False, "Admin": False, "Message": "Token expired."}

        except jwt.DecodeError:
            return {"Token": False, "Admin": False, "Message": "Failed to decode token."}

        except jwt.InvalidTokenError:
            return {"Token": False, "Admin": False, "Message": "Invalid token."} 
Example #25
Source File: jwt_manager.py    From Sanic-JWT-Extended with MIT License 5 votes vote down vote up
def _set_error_handlers(cls, app):
        app.error_handler.add(NoAuthorizationError, cls.handler.no_authorization)
        app.error_handler.add(ExpiredSignatureError, cls.handler.expired_signature)
        app.error_handler.add(InvalidHeaderError, cls.handler.invalid_header)
        app.error_handler.add(InvalidTokenError, cls.handler.invalid_token)
        app.error_handler.add(JWTDecodeError, cls.handler.jwt_decode_error)
        app.error_handler.add(WrongTokenError, cls.handler.wrong_token)
        app.error_handler.add(RevokedTokenError, cls.handler.revoked_token)
        app.error_handler.add(FreshTokenRequiredError, cls.handler.fresh_token_required)
        app.error_handler.add(AccessDeniedError, cls.handler.access_denied) 
Example #26
Source File: models.py    From flask-microservices-users with MIT License 5 votes vote down vote up
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.' 
Example #27
Source File: wrappers.py    From cloud-inquisitor with Apache License 2.0 5 votes vote down vote up
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() 
Example #28
Source File: users.py    From cride-platzi with MIT License 5 votes vote down vote up
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 
Example #29
Source File: test_utils.py    From django-oauth-toolkit-jwt with MIT License 5 votes vote down vote up
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) 
Example #30
Source File: service.py    From lemur with Apache License 2.0 4 votes vote down vote up
def login_required(f):
    """
    Validates the JWT and ensures that is has not expired and the user is still active.

    :param f:
    :return:
    """

    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not request.headers.get("Authorization"):
            response = jsonify(message="Missing authorization header")
            response.status_code = 401
            return response

        try:
            token = request.headers.get("Authorization").split()[1]
        except Exception as e:
            return dict(message="Token is invalid"), 403

        try:
            payload = jwt.decode(token, current_app.config["LEMUR_TOKEN_SECRET"])
        except jwt.DecodeError:
            return dict(message="Token is invalid"), 403
        except jwt.ExpiredSignatureError:
            return dict(message="Token has expired"), 403
        except jwt.InvalidTokenError:
            return dict(message="Token is invalid"), 403

        if "aid" in payload:
            access_key = api_key_service.get(payload["aid"])
            if access_key.revoked:
                return dict(message="Token has been revoked"), 403
            if access_key.ttl != -1:
                current_time = datetime.utcnow()
                expired_time = datetime.fromtimestamp(
                    access_key.issued_at + access_key.ttl
                )
                if current_time >= expired_time:
                    return dict(message="Token has expired"), 403

        user = user_service.get(payload["sub"])

        if not user.active:
            return dict(message="User is not currently active"), 403

        g.current_user = user

        if not g.current_user:
            return dict(message="You are not logged in"), 403

        # Tell Flask-Principal the identity changed
        identity_changed.send(
            current_app._get_current_object(), identity=Identity(g.current_user.id)
        )

        return f(*args, **kwargs)

    return decorated_function