How to use the jwt.ExpiredSignatureError function in jwt

To help you get started, we’ve selected a few jwt examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github vimalloc / flask-jwt-extended / tests / test_jwt_encode_decode.py View on Github external
def test_decode_invalid_jwt(self):
        with self.app.test_request_context():
            identity_claim = 'identity'
            # Verify underlying pyjwt expires verification works
            with self.assertRaises(jwt.ExpiredSignatureError):
                token_data = {
                    'exp': datetime.utcnow() - timedelta(minutes=5),
                }
                encoded_token = jwt.encode(token_data, 'secret', 'HS256').decode('utf-8')
                decode_jwt(encoded_token, 'secret', 'HS256',
                           csrf=False, identity_claim=identity_claim)

            # Missing jti
            with self.assertRaises(JWTDecodeError):

                token_data = {
                    'exp': datetime.utcnow() + timedelta(minutes=5),
                    identity_claim: 'banana',
                    'type': 'refresh'
                }
                encoded_token = jwt.encode(token_data, 'secret', 'HS256').decode('utf-8')
github vimalloc / flask-jwt-extended / tests / test_decode_tokens.py View on Github external
def test_expired_token(app, delta_func):
    with app.test_request_context():
        delta = delta_func(minutes=-5)
        access_token = create_access_token('username', expires_delta=delta)
        refresh_token = create_refresh_token('username', expires_delta=delta)
        with pytest.raises(ExpiredSignatureError):
            decode_token(access_token)
        with pytest.raises(ExpiredSignatureError):
            decode_token(refresh_token)
github blohinn / flask-restplus-full-todo-example-with-jwt / app / v1 / resources / auth.py View on Github external
_access_token = jwt.encode({'uid': refresh_token.user_id,
                                        'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=15),
                                        'iat': datetime.datetime.utcnow()},
                                       current_app.config['SECRET_KEY']).decode('utf-8')
            _refresh_token = jwt.encode({'uid': refresh_token.user_id,
                                         'exp': datetime.datetime.utcnow() + datetime.timedelta(days=30),
                                         'iat': datetime.datetime.utcnow()},
                                        current_app.config['SECRET_KEY']).decode('utf-8')

            refresh_token.refresh_token = _refresh_token
            db.session.add(refresh_token)
            db.session.commit()

            return {'access_token': _access_token, 'refresh_token': _refresh_token}, 200

        except jwt.ExpiredSignatureError as e:
            raise e
        except (jwt.DecodeError, jwt.InvalidTokenError)as e:
            raise e
        except:
            auth_ns.abort(401, 'Unknown token error')
github SamR1 / FitTrackee / fittrackee_api / fittrackee_api / users / models.py View on Github external
def decode_auth_token(auth_token):
        """
        Decodes the auth token
        :param auth_token: -
        :return: integer|string
        """
        try:
            return decode_user_token(auth_token)
        except jwt.ExpiredSignatureError:
            return 'Signature expired. Please log in again.'
        except jwt.InvalidTokenError:
            return 'Invalid token. Please log in again.'
github projectshift / shift-boiler / boiler / user / user_service.py View on Github external
def default_token_user_loader(self, token):
        """
        Default token user loader
        Accepts a token and decodes it checking signature and expiration. Then
        loads user by id from the token to see if account is not locked. If
        all is good, returns user record, otherwise throws an exception.

        :param token: str, token string
        :return: boiler.user.models.User
        """
        try:
            data = self.decode_token(token)
        except jwt.exceptions.DecodeError as e:
            raise x.JwtDecodeError(str(e))
        except jwt.ExpiredSignatureError as e:
            raise x.JwtExpired(str(e))

        user = self.get(data['user_id'])
        if not user:
            msg = 'No user with such id [{}]'
            raise x.JwtNoUser(msg.format(data['user_id']))

        if user.is_locked():
            msg = 'This account is locked'
            raise x.AccountLocked(msg, locked_until=user.locked_until)

        if self.require_confirmation and not user.email_confirmed:
            msg = 'Please confirm your email address [{}]'
            raise x.EmailNotConfirmed(
                msg.format(user.email_secure),
                email=user.email
github ismetacar / ertis / src / resources / security.py View on Github external
def validate_token(self, token, secret, verify):
        try:
            decoded = jwt.decode(token, key=secret, algorithms='HS256', verify=verify)

        except jwt.ExpiredSignatureError as e:
            raise ErtisError(
                status_code=401,
                err_msg="Provided token has expired",
                err_code="errors.tokenExpiredError",
                context={
                    'message': str(e)
                }
            )
        except Exception as e:
            raise ErtisError(
                status_code=401,
                err_msg="Provided token is invalid",
                err_code="errors.tokenIsInvalid",
                context={
                    'e': str(e)
                }
github matrix-org / synapse / synapse / rest / client / v1 / login.py View on Github external
def do_jwt_login(self, login_submission):
        token = login_submission.get("token", None)
        if token is None:
            raise LoginError(
                401, "Token field for JWT is missing",
                errcode=Codes.UNAUTHORIZED
            )

        import jwt
        from jwt.exceptions import InvalidTokenError

        try:
            payload = jwt.decode(token, self.jwt_secret, algorithms=[self.jwt_algorithm])
        except jwt.ExpiredSignatureError:
            raise LoginError(401, "JWT expired", errcode=Codes.UNAUTHORIZED)
        except InvalidTokenError:
            raise LoginError(401, "Invalid JWT", errcode=Codes.UNAUTHORIZED)

        user = payload.get("sub", None)
        if user is None:
            raise LoginError(401, "Invalid JWT", errcode=Codes.UNAUTHORIZED)

        user_id = UserID(user, self.hs.hostname).to_string()

        auth_handler = self.auth_handler
        registered_user_id = yield auth_handler.check_user_exists(user_id)
        if registered_user_id:
            device_id = login_submission.get("device_id")
            initial_display_name = login_submission.get("initial_device_display_name")
            device_id, access_token = yield self.registration_handler.register_device(
github Humanitec / django-oauth-toolkit-jwt / oauth2_provider_jwt / authentication.py View on Github external
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)
github p8ul / stackoverflow-lite / app / utils.py View on Github external
def decode_auth_token(auth_token):
    """ Validates the auth token
    :param auth_token:
    :return: integer|string
    """
    try:
        if is_blacklisted(auth_token):
            return 'Token has been blacklisted. Please log in again'
        payload = jwt.decode(auth_token, 'SECRET_KEY', algorithm='HS256')
        session['user_id'] = str(payload.get('sub'))
        return payload['sub']
    except jwt.ExpiredSignatureError:
        return 'Token Signature expired. Please log in again.'
    except jwt.InvalidTokenError:
        return 'Invalid token. Please log in again.'
github MD-Studio / MDStudio / core / auth / auth / application.py View on Github external
def verify_claims(self, signed_claims):
        try:
            claims = jwt_decode(signed_claims, self.jwt_key)
        except DecodeError:
            return {'error': 'Could not verify user'}
        except ExpiredSignatureError:
            return {'expired': 'Request token has expired'}

        return {'claims': claims}