Python jwt.exceptions() Examples

The following are 9 code examples of jwt.exceptions(). 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 , or try the search function .
Example #1
Source File: backends.py    From zulip with Apache License 2.0 6 votes vote down vote up
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 
Example #2
Source File: test_verifier.py    From asap-authentication-python with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: test_verifier.py    From asap-authentication-python with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: test_verifier.py    From asap-authentication-python with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: api_views.py    From mitoc-trips with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #6
Source File: backends.py    From zulip with Apache License 2.0 5 votes vote down vote up
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) 
Example #7
Source File: test_verifier.py    From asap-authentication-python with MIT License 5 votes vote down vote up
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) 
Example #8
Source File: test_verifier.py    From asap-authentication-python with MIT License 5 votes vote down vote up
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) 
Example #9
Source File: utils.py    From django-rest-framework-sso with MIT License 5 votes vote down vote up
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