當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。