当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.InvalidTokenError方法代码示例

本文整理汇总了Python中jwt.exceptions.InvalidTokenError方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.InvalidTokenError方法的具体用法?Python exceptions.InvalidTokenError怎么用?Python exceptions.InvalidTokenError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在jwt.exceptions的用法示例。


在下文中一共展示了exceptions.InvalidTokenError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _validate_token

# 需要导入模块: from jwt import exceptions [as 别名]
# 或者: from jwt.exceptions import InvalidTokenError [as 别名]
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) 
开发者ID:eigenmethod,项目名称:esia-connector,代码行数:19,代码来源:client.py

示例2: test_process_exception

# 需要导入模块: from jwt import exceptions [as 别名]
# 或者: from jwt.exceptions import InvalidTokenError [as 别名]
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) 
开发者ID:yunojuno,项目名称:django-request-token,代码行数:22,代码来源:test_middleware.py

示例3: verify_password_reset_token

# 需要导入模块: from jwt import exceptions [as 别名]
# 或者: from jwt.exceptions import InvalidTokenError [as 别名]
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 
开发者ID:tiangolo,项目名称:full-stack-fastapi-couchbase,代码行数:9,代码来源:utils.py

示例4: validate_jwt_request

# 需要导入模块: from jwt import exceptions [as 别名]
# 或者: from jwt.exceptions import InvalidTokenError [as 别名]
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") 
开发者ID:stellar,项目名称:django-polaris,代码行数:42,代码来源:utils.py

示例5: verify_password_reset_token

# 需要导入模块: from jwt import exceptions [as 别名]
# 或者: from jwt.exceptions import InvalidTokenError [as 别名]
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 
开发者ID:tiangolo,项目名称:full-stack-flask-couchbase,代码行数:9,代码来源:utils.py

示例6: verify_password_reset_token

# 需要导入模块: from jwt import exceptions [as 别名]
# 或者: from jwt.exceptions import InvalidTokenError [as 别名]
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 
开发者ID:QAX-A-Team,项目名称:LuWu,代码行数:9,代码来源:tools.py

示例7: process_exception

# 需要导入模块: from jwt import exceptions [as 别名]
# 或者: from jwt.exceptions import InvalidTokenError [as 别名]
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 
开发者ID:yunojuno,项目名称:django-request-token,代码行数:12,代码来源:middleware.py

示例8: authenticate

# 需要导入模块: from jwt import exceptions [as 别名]
# 或者: from jwt.exceptions import InvalidTokenError [as 别名]
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 
开发者ID:openzim,项目名称:zimfarm,代码行数:14,代码来源:__init__.py

示例9: auth_info_if_supplied

# 需要导入模块: from jwt import exceptions [as 别名]
# 或者: from jwt.exceptions import InvalidTokenError [as 别名]
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 
开发者ID:openzim,项目名称:zimfarm,代码行数:15,代码来源:__init__.py

示例10: register_handlers

# 需要导入模块: from jwt import exceptions [as 别名]
# 或者: from jwt.exceptions import InvalidTokenError [as 别名]
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 
开发者ID:openzim,项目名称:zimfarm,代码行数:30,代码来源:__init__.py

示例11: _handle_token

# 需要导入模块: from jwt import exceptions [as 别名]
# 或者: from jwt.exceptions import InvalidTokenError [as 别名]
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) 
开发者ID:joegasewicz,项目名称:flask-jwt-router,代码行数:30,代码来源:_routing.py

示例12: authenticate_session_helper

# 需要导入模块: from jwt import exceptions [as 别名]
# 或者: from jwt.exceptions import InvalidTokenError [as 别名]
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"]] 
开发者ID:stellar,项目名称:django-polaris,代码行数:59,代码来源:utils.py

示例13: _restrict_asap

# 需要导入模块: from jwt import exceptions [as 别名]
# 或者: from jwt.exceptions import InvalidTokenError [as 别名]
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 
开发者ID:atlassian,项目名称:asap-authentication-python,代码行数:46,代码来源:decorators.py

示例14: __call__

# 需要导入模块: from jwt import exceptions [as 别名]
# 或者: from jwt.exceptions import InvalidTokenError [as 别名]
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) 
开发者ID:yunojuno,项目名称:django-request-token,代码行数:59,代码来源:middleware.py

示例15: log

# 需要导入模块: from jwt import exceptions [as 别名]
# 或者: from jwt.exceptions import InvalidTokenError [as 别名]
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 
开发者ID:yunojuno,项目名称:django-request-token,代码行数:44,代码来源:models.py


注:本文中的jwt.exceptions.InvalidTokenError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。