Python jwt.exceptions.InvalidTokenError() Examples

The following are 16 code examples of jwt.exceptions.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.exceptions , or try the search function .
Example #1
Source File: client.py    From esia-connector with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _validate_token(self, token):
        """
        :param str token: token to validate
        """
        if self.settings.esia_token_check_key is None:
            raise ValueError("To validate token you need to specify `esia_token_check_key` in settings!")

        with open(self.settings.esia_token_check_key, 'r') as f:
            data = f.read()

        try:
            return jwt.decode(token,
                              key=data,
                              audience=self.settings.esia_client_id,
                              issuer=self._ESIA_ISSUER_NAME)
        except InvalidTokenError as e:
            raise IncorrectMarkerError(e) 
Example #2
Source File: test_middleware.py    From django-request-token with MIT License 6 votes vote down vote up
def test_process_exception(self, mock_log):
        request = self.get_request()
        request.token = self.token
        exception = exceptions.InvalidTokenError("bar")
        response = self.middleware.process_exception(request, exception)
        mock_log.assert_called_once_with(request, response, error=exception)
        self.assertEqual(response.status_code, 403)
        self.assertEqual(response.reason_phrase, str(exception))

        # no request token = no error log
        del request.token
        mock_log.reset_mock()
        response = self.middleware.process_exception(request, exception)
        self.assertEqual(mock_log.call_count, 0)
        self.assertEqual(response.status_code, 403)
        self.assertEqual(response.reason_phrase, str(exception))

        # round it out with a non-token error
        response = self.middleware.process_exception(request, Exception("foo"))
        self.assertIsNone(response) 
Example #3
Source File: utils.py    From full-stack-fastapi-couchbase with MIT License 5 votes vote down vote up
def verify_password_reset_token(token) -> Optional[str]:
    try:
        decoded_token = jwt.decode(token, config.SECRET_KEY, algorithms=["HS256"])
        assert decoded_token["sub"] == password_reset_jwt_subject
        return decoded_token["username"]
    except InvalidTokenError:
        return None 
Example #4
Source File: utils.py    From django-polaris with Apache License 2.0 5 votes vote down vote up
def validate_jwt_request(request: Request) -> str:
    """
    Validate the JSON web token in a request and return the source account address

    :raises ValueError: invalid JWT
    """
    # While the SEP 24 spec calls the authorization header "Authorization", django middleware
    # renames this as "HTTP_AUTHORIZATION". We check this header for the JWT.
    jwt_header = request.META.get("HTTP_AUTHORIZATION")
    if not jwt_header:
        raise ValueError("JWT must be passed as 'Authorization' header")
    bad_format_error = ValueError(
        "'Authorization' header must be formatted as 'Bearer <token>'"
    )
    if "Bearer" not in jwt_header:
        raise bad_format_error
    try:
        encoded_jwt = jwt_header.split(" ")[1]
    except IndexError:
        raise bad_format_error
    if not encoded_jwt:
        raise bad_format_error
    # Validate the JWT contents.
    try:
        jwt_dict = jwt.decode(
            encoded_jwt, settings.SERVER_JWT_KEY, algorithms=["HS256"]
        )
    except InvalidTokenError as e:
        raise ValueError("Unable to decode jwt")

    if jwt_dict["iss"] != os.path.join(settings.HOST_URL, "auth"):
        raise ValueError("'jwt' has incorrect 'issuer'")
    current_time = time.time()
    if current_time < jwt_dict["iat"] or current_time > jwt_dict["exp"]:
        raise ValueError("'jwt' is no longer valid")

    try:
        return jwt_dict["sub"]
    except KeyError:
        raise ValueError("Decoded JWT missing 'sub' field") 
Example #5
Source File: utils.py    From full-stack-flask-couchbase with MIT License 5 votes vote down vote up
def verify_password_reset_token(token) -> Union[str, bool]:
    try:
        decoded_token = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
        assert decoded_token["sub"] == password_reset_jwt_subject
        return decoded_token["username"]
    except InvalidTokenError:
        return False 
Example #6
Source File: tools.py    From LuWu with Apache License 2.0 5 votes vote down vote up
def verify_password_reset_token(token) -> Optional[str]:
    try:
        decoded_token = jwt.decode(token, config.SECRET_KEY, algorithms=["HS256"])
        assert decoded_token["sub"] == password_reset_jwt_subject
        return decoded_token["email"]
    except InvalidTokenError:
        return None 
Example #7
Source File: middleware.py    From django-request-token with MIT License 5 votes vote down vote up
def process_exception(
        self, request: HttpRequest, exception: Exception
    ) -> HttpResponse:
        """Handle all InvalidTokenErrors."""
        if isinstance(exception, InvalidTokenError):
            logger.exception("JWT request token error")
            response = _403(request, exception)
            if getattr(request, "token", None):
                request.token.log(request, response, error=exception)
            return response 
Example #8
Source File: __init__.py    From zimfarm with GNU General Public License v3.0 5 votes vote down vote up
def authenticate(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        try:
            kwargs["token"] = token_from_request(request)
            return f(*args, **kwargs)
        except jwt_exceptions.ExpiredSignatureError:
            raise Unauthorized("token expired")
        except (jwt_exceptions.InvalidTokenError, jwt_exceptions.PyJWTError):
            raise Unauthorized("token invalid")

    return wrapper 
Example #9
Source File: __init__.py    From zimfarm with GNU General Public License v3.0 5 votes vote down vote up
def auth_info_if_supplied(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        kwargs["token"] = None
        try:
            kwargs["token"] = token_from_request(request)
        except jwt_exceptions.ExpiredSignatureError:
            kwargs["token"] = None
        except (jwt_exceptions.InvalidTokenError, jwt_exceptions.PyJWTError):
            kwargs["token"] = None
        return f(*args, **kwargs)

    return wrapper 
Example #10
Source File: __init__.py    From zimfarm with GNU General Public License v3.0 5 votes vote down vote up
def register_handlers(app: Flask):
    app.errorhandler(BadRequest)(BadRequest.handler)
    app.errorhandler(OfflinerConfigNotValid)(OfflinerConfigNotValid.handler)
    app.errorhandler(Unauthorized)(Unauthorized.handler)
    app.errorhandler(NotFound)(NotFound.handler)
    app.errorhandler(InternalError)(InternalError.handler)

    app.errorhandler(oauth2.OAuth2Base)(oauth2.handler)
    app.errorhandler(http.HTTPBase)(http.handler)

    @app.errorhandler(marshmallow.exceptions.ValidationError)
    def handler_validationerror(e):
        return make_response(jsonify({"message": e.messages}), HTTPStatus.BAD_REQUEST)

    @app.errorhandler(jwt_exceptions.ExpiredSignature)
    def handler_expiredsig(_):
        return make_response(
            jsonify({"error": "token expired"}), HTTPStatus.UNAUTHORIZED
        )

    @app.errorhandler(jwt_exceptions.InvalidTokenError)
    def handler_invalidtoken(_):
        return make_response(
            jsonify({"error": "token invalid"}), HTTPStatus.UNAUTHORIZED
        )


# 400 
Example #11
Source File: _routing.py    From flask-jwt-router with GNU General Public License v3.0 5 votes vote down vote up
def _handle_token(self):
        """
        Checks the headers contain a Bearer string OR params.
        Checks to see that the route is white listed.
        :return None:
        """
        try:
            if request.args.get("auth"):
                token = request.args.get("auth")
            else:
                bearer = request.headers.get("Authorization")
                token = bearer.split("Bearer ")[1]
        except AttributeError:
            return abort(401)
        try:
            decoded_token = jwt.decode(
                token,
                self.extensions.secret_key,
                algorithms="HS256"
            )
        except InvalidTokenError:
            return abort(401)
        try:
            entity = self.entity.get_entity_from_token(decoded_token)
            setattr(g, self.entity.get_entity_from_ext().__tablename__, entity)
            return None
        except ValueError:
            return abort(401) 
Example #12
Source File: utils.py    From django-polaris with Apache License 2.0 4 votes vote down vote up
def authenticate_session_helper(r: Request):
    """
    Decodes and validates the JWT token passed in the GET request to a
    /webapp endpoint.

    Adds two items to ``r.session``:
    - authenticated: a boolean for whether the session has been authenticated
        for any transaction
    - account: the stellar account address associated with the token
    """
    # Don't authenticate in local mode, since session cookies will not be
    # included in request/response headers without HTTPS
    if settings.LOCAL_MODE:
        return

    token = r.GET.get("token")
    if not token:
        # If there is no token, check if this session has already been authenticated,
        # that the session's account is the one that initiated the transaction, and
        # that the session has been authenticated for this particular transaction.
        if r.session.get("authenticated") and r.session.get("account", ""):
            tid = r.GET.get("transaction_id")
            tqs = Transaction.objects.filter(
                id=tid, stellar_account=r.session["account"]
            )
            if not (tid in r.session.get("transactions", []) and tqs.exists()):
                raise ValueError(f"Not authenticated for transaction ID: {tid}")
            else:  # pragma: no cover
                # client has been authenticated for the requested transaction
                return
        else:
            raise ValueError("Missing authentication token")

    try:
        jwt_dict = jwt.decode(token, settings.SERVER_JWT_KEY, algorithms=["HS256"])
    except InvalidTokenError as e:
        raise ValueError(str(e))

    now = time.time()
    if jwt_dict["iss"] != r.build_absolute_uri("interactive"):
        raise ValueError(_("Invalid token issuer"))
    elif jwt_dict["iat"] > now or jwt_dict["exp"] < now:
        raise ValueError(_("Token is not yet valid or is expired"))

    transaction_qs = Transaction.objects.filter(
        id=jwt_dict["jti"], stellar_account=jwt_dict["sub"]
    )
    if not transaction_qs.exists():
        raise ValueError(_("Transaction for account not found"))

    # JWT is valid, authenticate session
    r.session["authenticated"] = True
    r.session["account"] = jwt_dict["sub"]
    try:
        r.session["transactions"].append(jwt_dict["jti"])
    except KeyError:
        r.session["transactions"] = [jwt_dict["jti"]] 
Example #13
Source File: decorators.py    From asap-authentication-python with MIT License 4 votes vote down vote up
def _restrict_asap(func=None, backend=None, issuers=None,
                   required=True, subject_should_match_issuer=None):
    """Decorator to allow endpoint-specific ASAP authorization, assuming ASAP
    authentication has already occurred.
    """

    def restrict_asap_decorator(func):
        @wraps(func)
        def restrict_asap_wrapper(request, *args, **kwargs):
            settings = _update_settings_from_kwargs(
                backend.settings,
                issuers=issuers, required=required,
                subject_should_match_issuer=subject_should_match_issuer
            )
            asap_claims = getattr(request, 'asap_claims', None)
            error_response = None

            if required and not asap_claims:
                return backend.get_401_response(
                    'Unauthorized', request=request
                )

            try:
                _verify_issuers(asap_claims, settings.ASAP_VALID_ISSUERS)
            except InvalidIssuerError:
                error_response = backend.get_403_response(
                    'Forbidden: Invalid token issuer', request=request
                )
            except InvalidTokenError:
                error_response = backend.get_401_response(
                    'Unauthorized: Invalid token', request=request
                )

            if error_response and required:
                return error_response

            return func(request, *args, **kwargs)

        return restrict_asap_wrapper

    if callable(func):
        return restrict_asap_decorator(func)

    return restrict_asap_decorator 
Example #14
Source File: middleware.py    From django-request-token with MIT License 4 votes vote down vote up
def __call__(self, request: HttpRequest) -> HttpResponse:  # noqa: C901
        """
        Verify JWT request querystring arg.

        If a token is found (using JWT_QUERYSTRING_ARG), then it is decoded,
        which verifies the signature and expiry dates, and raises a 403 if
        the token is invalid.

        The decoded payload is then added to the request as the `token_payload`
        property - allowing it to be interrogated by the view function
        decorator when it gets there.

        We don't substitute in the user at this point, as we are not making
        any assumptions about the request path at this point - it's not until
        we get to the view function that we know where we are heading - at
        which point we verify that the scope matches, and only then do we
        use the token user.

        """
        if not hasattr(request, "session"):
            raise ImproperlyConfigured(
                "Request has no session attribute, please ensure that Django "
                "session middleware is installed."
            )
        if not hasattr(request, "user"):
            raise ImproperlyConfigured(
                "Request has no user attribute, please ensure that Django "
                "authentication middleware is installed."
            )

        if request.method == "GET" or request.method == "POST":
            token = request.GET.get(JWT_QUERYSTRING_ARG)
            if not token and request.method == "POST":
                if request.META.get("CONTENT_TYPE") == "application/json":
                    token = json.loads(request.body).get(JWT_QUERYSTRING_ARG)
                if not token:
                    token = request.POST.get(JWT_QUERYSTRING_ARG)
        else:
            token = None

        if token is None:
            return self.get_response(request)

        # in the event of an error we log it, but then let the request
        # continue - as the fact that the token cannot be decoded, or
        # no longer exists, may not invalidate the request itself.
        try:
            payload = decode(token)
            request.token = RequestToken.objects.get(id=payload["jti"])
        except RequestToken.DoesNotExist:
            request.token = None
            logger.exception("RequestToken no longer exists: %s", payload["jti"])
        except InvalidTokenError:
            request.token = None
            logger.exception("RequestToken cannot be decoded: %s", token)

        return self.get_response(request) 
Example #15
Source File: models.py    From django-request-token with MIT License 4 votes vote down vote up
def log(
        self,
        request: HttpRequest,
        response: HttpResponse,
        error: Optional[InvalidTokenError] = None,
    ) -> RequestTokenLog:
        """
        Record the use of a token.

        This is used by the decorator to log each time someone uses the token,
        or tries to. Used for reporting, diagnostics.

        Args:
            request: the HttpRequest object that used the token, from which the
                user, ip and user-agenct are extracted.
            response: the corresponding HttpResponse object, from which the status
                code is extracted.
            error: an InvalidTokenError that gets logged as a RequestTokenError.

        Returns a RequestTokenUse object.

        """

        def rmg(key: str, default: Any = None) -> Any:
            return request.META.get(key, default)

        log = RequestTokenLog(
            token=self,
            user=None if request.user.is_anonymous else request.user,
            user_agent=rmg("HTTP_USER_AGENT", "unknown"),
            client_ip=parse_xff(rmg("HTTP_X_FORWARDED_FOR"))
            or rmg("REMOTE_ADDR", None),
            status_code=response.status_code,
        ).save()
        if error and LOG_TOKEN_ERRORS:
            RequestTokenErrorLog.objects.create_error_log(log, error)
        # NB this will include all error logs - which means that an error log
        # may prohibit further use of the token. Is there a scenario in which
        # this would be the wrong outcome?
        self.used_to_date = self.logs.filter(error__isnull=True).count()
        self.save()
        return log 
Example #16
Source File: utils.py    From django-rest-framework-sso with MIT License 4 votes vote down vote up
def decode_jwt_token(token):
    unverified_header = jwt.get_unverified_header(token)
    unverified_claims = jwt.decode(token, verify=False)

    if unverified_header.get(claims.KEY_ID):
        unverified_key_id = str(unverified_header.get(claims.KEY_ID))
    else:
        unverified_key_id = None

    if claims.ISSUER not in unverified_claims:
        raise MissingRequiredClaimError(claims.ISSUER)

    unverified_issuer = str(unverified_claims[claims.ISSUER])

    if api_settings.ACCEPTED_ISSUERS is not None and unverified_issuer not in api_settings.ACCEPTED_ISSUERS:
        raise InvalidIssuerError("Invalid issuer")

    public_key, key_id = get_public_key_and_key_id(issuer=unverified_issuer, key_id=unverified_key_id)

    options = {
        "verify_exp": api_settings.VERIFY_EXPIRATION,
        "verify_iss": api_settings.VERIFY_ISSUER,
        "verify_aud": api_settings.VERIFY_AUDIENCE,
    }

    payload = jwt.decode(
        jwt=token,
        key=public_key,
        verify=api_settings.VERIFY_SIGNATURE,
        algorithms=api_settings.DECODE_ALGORITHMS or [api_settings.ENCODE_ALGORITHM],
        options=options,
        leeway=api_settings.EXPIRATION_LEEWAY,
        audience=api_settings.IDENTITY,
        issuer=unverified_issuer,
    )

    if payload.get(claims.TOKEN) not in (claims.TOKEN_SESSION, claims.TOKEN_AUTHORIZATION):
        raise InvalidTokenError("Unknown token type")
    if not payload.get(claims.SESSION_ID):
        raise MissingRequiredClaimError("Session ID is missing.")
    if not payload.get(claims.USER_ID):
        raise MissingRequiredClaimError("User ID is missing.")

    return payload