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


Python jwt.exceptions方法代码示例

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


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

示例1: auth_complete

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import exceptions [as 别名]
def auth_complete(self, *args: Any, **kwargs: Any) -> Optional[HttpResponse]:
        """This is a small wrapper around the core `auth_complete` method of
        python-social-auth, designed primarily to prevent 500s for
        exceptions in the social auth code from situations that are
        really user errors.  Returning `None` from this function will
        redirect the browser to the login page.
        """
        try:
            # Call the auth_complete method of social_core.backends.oauth.BaseOAuth2
            return super().auth_complete(*args, **kwargs)
        except (AuthFailed, HTTPError) as e:
            # When a user's social authentication fails (e.g. because
            # they did something funny with reloading in the middle of
            # the flow or the IdP is unreliable and returns a bad http response),
            # don't throw a 500, just send them back to the
            # login page and record the event at the info log level.
            self.logger.info("%s: %s", e.__class__.__name__, str(e))
            return None
        except SocialAuthBaseException as e:
            # Other python-social-auth exceptions are likely
            # interesting enough that we should log a warning.
            self.logger.warning(str(e))
            return None 
开发者ID:zulip,项目名称:zulip,代码行数:25,代码来源:backends.py

示例2: test_verify_jwt_with_none_algorithm

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import exceptions [as 别名]
def test_verify_jwt_with_none_algorithm(self):
        """ tests that verify_jwt does not accept jwt that use the none
            algorithm.
        """
        verifier = self._setup_jwt_auth_verifier(self._public_key_pem)
        private_key_ret = atlassian_jwt_auth.key.StaticPrivateKeyRetriever(
            self._example_key_id, self._private_key_pem.decode())
        jwt_signer = NoneAlgorithmJwtAuthSigner(
            issuer=self._example_issuer,
            private_key_retriever=private_key_ret,
        )
        for algorithm in ['none', 'None', 'nOne', 'nonE', 'NONE']:
            jwt_token = jwt_signer.generate_jwt(
                self._example_aud, alg_header=algorithm)
            jwt_headers = jwt.get_unverified_header(jwt_token)
            self.assertEqual(jwt_headers['alg'], algorithm)
            with self.assertRaises(jwt.exceptions.InvalidAlgorithmError):
                verifier.verify_jwt(jwt_token, self._example_aud) 
开发者ID:atlassian,项目名称:asap-authentication-python,代码行数:20,代码来源:test_verifier.py

示例3: test_verify_jwt_with_non_matching_sub_and_iss

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import exceptions [as 别名]
def test_verify_jwt_with_non_matching_sub_and_iss(self, m_j_decode):
        """ tests that verify_jwt rejects a jwt if the claims
            contains a subject which does not match the issuer.
        """
        expected_msg = 'Issuer does not match the subject'
        m_j_decode.return_value = {
            'iss': self._example_issuer,
            'sub': self._example_issuer[::-1]
        }
        a_jwt = self._jwt_auth_signer.generate_jwt(self._example_aud)
        verifier = self._setup_jwt_auth_verifier(self._public_key_pem)
        for exception in [
            ValueError,
            atlassian_jwt_auth.exceptions.SubjectDoesNotMatchIssuerException,
        ]:
            with self.assertRaisesRegexp(exception, expected_msg):
                verifier.verify_jwt(a_jwt, self._example_aud) 
开发者ID:atlassian,项目名称:asap-authentication-python,代码行数:19,代码来源:test_verifier.py

示例4: test_verify_jwt_with_jwt_with_already_seen_jti

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import exceptions [as 别名]
def test_verify_jwt_with_jwt_with_already_seen_jti(self):
        """ tests that verify_jwt rejects a jwt if the jti
            has already been seen.
        """
        verifier = self._setup_jwt_auth_verifier(
            self._public_key_pem, check_jti_uniqueness=True)
        a_jwt = self._jwt_auth_signer.generate_jwt(
            self._example_aud)
        self.assertIsNotNone(verifier.verify_jwt(
            a_jwt,
            self._example_aud))
        for exception in [
                ValueError,
                atlassian_jwt_auth.exceptions.JtiUniquenessException]:
            with self.assertRaisesRegexp(exception, 'has already been used'):
                verifier.verify_jwt(a_jwt, self._example_aud) 
开发者ID:atlassian,项目名称:asap-authentication-python,代码行数:18,代码来源:test_verifier.py

示例5: dispatch

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import exceptions [as 别名]
def dispatch(self, request, *args, **kwargs):
        """ Verify & decode JWT, storing its payload.

        Disable CSRF validation on these requests, since they will be
        all be cross-origin, and validation is done entirely by JWT.
        """
        try:
            token = jwt_token_from_headers(request)
        except ValueError:
            return JsonResponse({'message': 'token missing'}, status=401)

        secret = settings.MEMBERSHIP_SECRET_KEY
        try:
            self.payload = jwt.decode(token, secret)
        except (jwt.exceptions.InvalidTokenError, KeyError):
            return JsonResponse({'message': 'invalid token'}, status=401)

        return super().dispatch(request, *args, **kwargs) 
开发者ID:DavidCain,项目名称:mitoc-trips,代码行数:20,代码来源:api_views.py

示例6: _check_entitlements

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import exceptions [as 别名]
def _check_entitlements(self, idp: SAMLIdentityProvider, attributes: Dict[str, List[str]]) -> None:
        """
        Below is the docstring from the social_core SAML backend.

        Additional verification of a SAML response before
        authenticating the user.

        Subclasses can override this method if they need custom
        validation code, such as requiring the presence of an
        eduPersonEntitlement.

        raise social_core.exceptions.AuthForbidden if the user should not
        be authenticated, or do nothing to allow the login pipeline to
        continue.
        """
        org_membership_attribute = idp.conf.get('attr_org_membership', None)
        if org_membership_attribute is None:
            return

        subdomain = self.strategy.session_get('subdomain')
        entitlements: Union[str, List[str]] = attributes.get(org_membership_attribute, [])
        if subdomain in entitlements:
            return

        # The root subdomain is a special case, as sending an
        # empty string in the list of values of the attribute may
        # not be viable. So, any of the ROOT_SUBDOMAIN_ALIASES can
        # be used to signify the user is authorized for the root
        # subdomain.
        if (subdomain == Realm.SUBDOMAIN_FOR_ROOT_DOMAIN
                and not settings.ROOT_DOMAIN_LANDING_PAGE
                and any(alias in entitlements for alias in settings.ROOT_SUBDOMAIN_ALIASES)):
            return

        error_msg = f"SAML user from IdP {idp.name} rejected due to missing entitlement " + \
                    f"for subdomain '{subdomain}'. User entitlements: {entitlements}."
        raise AuthFailed(self, error_msg) 
开发者ID:zulip,项目名称:zulip,代码行数:39,代码来源:backends.py

示例7: test_verify_jwt_with_none_aud

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import exceptions [as 别名]
def test_verify_jwt_with_none_aud(self):
        """ tests that verify_jwt rejects jwt that have a None aud claim. """
        verifier = self._setup_jwt_auth_verifier(self._public_key_pem)
        a_jwt = self._jwt_auth_signer.generate_jwt(
            self._example_aud,
            additional_claims={'aud': None})
        with self.assertRaises(jwt.exceptions.InvalidAudienceError):
            verifier.verify_jwt(a_jwt, self._example_aud) 
开发者ID:atlassian,项目名称:asap-authentication-python,代码行数:10,代码来源:test_verifier.py

示例8: test_verify_jwt_with_non_matching_aud

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import exceptions [as 别名]
def test_verify_jwt_with_non_matching_aud(self):
        """ tests that verify_jwt rejects a jwt if the aud claim does not
            match the given & expected audience.
        """
        verifier = self._setup_jwt_auth_verifier(self._public_key_pem)
        a_jwt = self._jwt_auth_signer.generate_jwt(
            self._example_aud,
            additional_claims={'aud': self._example_aud + '-different'})
        with self.assertRaises(jwt.exceptions.InvalidAudienceError):
            verifier.verify_jwt(a_jwt, self._example_aud) 
开发者ID:atlassian,项目名称:asap-authentication-python,代码行数:12,代码来源:test_verifier.py

示例9: authenticate_payload

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import exceptions [as 别名]
def authenticate_payload(payload, request=None):
    from rest_framework_sso.models import SessionToken

    user_model = get_user_model()

    if api_settings.VERIFY_SESSION_TOKEN:
        try:
            session_token = (
                SessionToken.objects.active()
                .select_related("user")
                .get(pk=payload.get(claims.SESSION_ID), user_id=payload.get(claims.USER_ID))
            )
            if request is not None:
                session_token.update_attributes(request=request)
            session_token.last_used_at = timezone.now()
            session_token.save()
            user = session_token.user
        except SessionToken.DoesNotExist:
            raise exceptions.AuthenticationFailed(_("Invalid token."))
    else:
        try:
            user = user_model.objects.get(pk=payload.get(claims.USER_ID))
        except user_model.DoesNotExist:
            raise exceptions.AuthenticationFailed(_("Invalid token."))

    if not user.is_active:
        raise exceptions.AuthenticationFailed(_("User inactive or deleted."))

    return user 
开发者ID:namespace-ee,项目名称:django-rest-framework-sso,代码行数:31,代码来源:utils.py


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