How to use the oauthlib.oauth2.rfc6749.errors function in oauthlib

To help you get started, we’ve selected a few oauthlib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github oauthlib / oauthlib / tests / oauth2 / rfc6749 / test_servers.py View on Github external
uri.format('code'), scopes=['foo'])
            self.assertEqual(s, 302)
            self.assertIn('Location', h)
            self.assertIn('error=invalid_request', h['Location'])
        invalid_bodies = [
            # duplicate params
            'grant_type=authorization_code&client_id=nope&client_id=nope&code=foo'
        ]
        for body in invalid_bodies:
            _, body, _ = self.web.create_token_response(token_uri,
                    body=body)
            self.assertEqual('invalid_request', json.loads(body)['error'])

        # Implicit grant
        for uri in invalid_uris:
            self.assertRaises(errors.InvalidRequestError,
                    self.mobile.validate_authorization_request,
                    uri.format('token'))
            h, _, s = self.mobile.create_authorization_response(
                    uri.format('token'), scopes=['foo'])
            self.assertEqual(s, 302)
            self.assertIn('Location', h)
            self.assertIn('error=invalid_request', h['Location'])

        # Password credentials grant
        invalid_bodies = [
            # duplicate params
            'grant_type=password&username=foo&username=bar&password=baz'
            # missing username
            'grant_type=password&password=baz'
            # missing password
            'grant_type=password&username=foo'
github oauthlib / oauthlib / tests / oauth2 / rfc6749 / grant_types / test_authorization_code.py View on Github external
def test_pkce_required_verifier_missing_challenge_valid(self):
        self.mock_validator.is_pkce_required.return_value = True
        self.request.code_verifier = None
        self.mock_validator.get_code_challenge.return_value = "foo"
        self.assertRaises(errors.MissingCodeVerifierError,
                          self.auth.validate_token_request, self.request)
github oauthlib / oauthlib / tests / oauth2 / rfc6749 / grant_types / test_resource_owner_password.py View on Github external
def test_invalid_grant_type(self):
        self.request.grant_type = 'foo'
        self.assertRaises(errors.UnsupportedGrantTypeError,
                          self.auth.validate_token_request, self.request)
github oauthlib / oauthlib / oauthlib / oauth2 / rfc6749 / grant_types / authorization_code.py View on Github external
# fails for reasons other than a missing or invalid redirection URI,
        # the authorization server informs the client by adding the following
        # parameters to the query component of the redirection URI using the
        # "application/x-www-form-urlencoded" format, per Appendix B.
        # https://tools.ietf.org/html/rfc6749#appendix-B

        # Note that the correct parameters to be added are automatically
        # populated through the use of specific exceptions.

        request_info = {}
        for validator in self.custom_validators.pre_auth:
            request_info.update(validator(request))

        # REQUIRED.
        if request.response_type is None:
            raise errors.MissingResponseTypeError(request=request)
        # Value MUST be set to "code" or one of the OpenID authorization code including
        # response_types "code token", "code id_token", "code token id_token"
        elif not 'code' in request.response_type and request.response_type != 'none':
            raise errors.UnsupportedResponseTypeError(request=request)

        if not self.request_validator.validate_response_type(request.client_id,
                                                             request.response_type,
                                                             request.client, request):

            log.debug('Client %s is not authorized to use response_type %s.',
                      request.client_id, request.response_type)
            raise errors.UnauthorizedClientError(request=request)

        # OPTIONAL. Validate PKCE request or reply with "error"/"invalid_request"
        # https://tools.ietf.org/html/rfc6749#section-4.4.1
        if self.request_validator.is_pkce_required(request.client_id, request) is True:
github oauthlib / oauthlib / oauthlib / oauth2 / rfc6749 / grant_types / client_credentials.py View on Github external
def validate_token_request(self, request):
        """
        :param request: OAuthlib request.
        :type request: oauthlib.common.Request
        """
        for validator in self.custom_validators.pre_token:
            validator(request)

        if not getattr(request, 'grant_type', None):
            raise errors.InvalidRequestError('Request is missing grant type.',
                                             request=request)

        if not request.grant_type == 'client_credentials':
            raise errors.UnsupportedGrantTypeError(request=request)

        for param in ('grant_type', 'scope'):
            if param in request.duplicate_params:
                raise errors.InvalidRequestError(description='Duplicate %s parameter.' % param,
                                                 request=request)

        log.debug('Authenticating client, %r.', request)
        if not self.request_validator.authenticate_client(request):
            log.debug('Client authentication failed, %r.', request)
            raise errors.InvalidClientError(request=request)
        else:
            if not hasattr(request.client, 'client_id'):
                raise NotImplementedError('Authenticate client must set the '
                                          'request.client.client_id attribute '
                                          'in authenticate_client.')
        # Ensure client is authorized use of this grant type
github filiph / progress_bar / gae / oauthlib / oauth2 / rfc6749 / grant_types / base.py View on Github external
def validate_grant_type(self, request):
        if not self.request_validator.validate_grant_type(request.client_id,
                                                          request.grant_type, request.client, request):
            log.debug('Unauthorized from %r (%r) access to grant type %s.',
                      request.client_id, request.client, request.grant_type)
            raise errors.UnauthorizedClientError(request=request)
github Royal-Society-of-New-Zealand / NZ-ORCID-Hub / authcontroller.py View on Github external
try:
        state = request.args['state']
        if state != session.get('oauth_state'):
            flash(
                "Retry giving permissions or if issue persist then, Please contact ORCIDHUB for support",
                "danger")
            app.logger.error(
                "For %r session state was %r, whereas state returned from ORCID is %r",
                current_user, session.get('oauth_state', 'empty'), state)
            return redirect(url_for("login"))

        token = client.fetch_token(
            TOKEN_URL,
            client_secret=current_user.organisation.orcid_secret,
            authorization_response=request.url)
    except rfc6749.errors.MissingCodeError:
        flash("%s cannot be invoked directly..." % request.url, "danger")
        return redirect(url_for("login"))
    except rfc6749.errors.MissingTokenError:
        flash("Missing token.", "danger")
        return redirect(url_for("login"))
    except Exception as ex:
        flash("Something went wrong contact orcidhub support for issue: %s" % str(ex))
        app.logger.error("For %r encountered exception: %r", current_user, ex)
        return redirect(url_for("login"))

    # At this point you can fetch protected resources but lets save
    # the token and show how this is done from a persisted token
    # in /profile.
    session['oauth_token'] = token
    orcid = token['orcid']
    name = token["name"]
github oauthlib / oauthlib / oauthlib / oauth2 / rfc6749 / grant_types / authorization_code.py View on Github external
.. _`Section 2.2`: https://tools.ietf.org/html/rfc6749#section-2.2
        .. _`Section 3.1.2`: https://tools.ietf.org/html/rfc6749#section-3.1.2
        .. _`Section 3.3`: https://tools.ietf.org/html/rfc6749#section-3.3
        .. _`Section 10.12`: https://tools.ietf.org/html/rfc6749#section-10.12
        """
        try:
            self.validate_authorization_request(request)
            log.debug('Pre resource owner authorization validation ok for %r.',
                      request)

        # If the request fails due to a missing, invalid, or mismatching
        # redirection URI, or if the client identifier is missing or invalid,
        # the authorization server SHOULD inform the resource owner of the
        # error and MUST NOT automatically redirect the user-agent to the
        # invalid redirection URI.
        except errors.FatalClientError as e:
            log.debug('Fatal client error during validation of %r. %r.',
                      request, e)
            raise

        # If the resource owner denies the access request or if the request
        # fails for reasons other than a missing or invalid redirection URI,
        # the authorization server informs the client by adding the following
        # parameters to the query component of the redirection URI using the
        # "application/x-www-form-urlencoded" format, per Appendix B:
        # https://tools.ietf.org/html/rfc6749#appendix-B
        except errors.OAuth2Error as e:
            log.debug('Client error during validation of %r. %r.', request, e)
            request.redirect_uri = request.redirect_uri or self.error_uri
            redirect_uri = common.add_params_to_uri(
                request.redirect_uri, e.twotuples,
                fragment=request.response_mode == "fragment")
github hypothesis / h / h / oauth / jwt_grant.py View on Github external
"""

        try:
            assertion = request.assertion
        except AttributeError:
            raise errors.InvalidRequestFatalError("Missing assertion.")

        token = JWTGrantToken(assertion)

        # Update client_id in oauthlib request
        request.client_id = token.issuer

        if not self.request_validator.authenticate_client_id(
            request.client_id, request
        ):
            raise errors.InvalidClientError(request=request)

        # Ensure client is authorized use of this grant type
        self.validate_grant_type(request)

        authclient = request.client.authclient

        verified_token = token.verified(key=authclient.secret, audience=self.domain)

        user = self.user_svc.fetch(verified_token.subject)
        if user is None:
            raise errors.InvalidGrantError(
                "Grant token subject (sub) could not be found."
            )

        if user.authority != authclient.authority:
            raise errors.InvalidGrantError(
github oauthlib / oauthlib / oauthlib / oauth2 / rfc6749 / grant_types / authorization_code.py View on Github external
raise errors.InvalidGrantError(request=request, description="Challenge method not found")

            if challenge_method not in self._code_challenge_methods:
                raise errors.ServerError(
                    description="code_challenge_method {} is not supported.".format(challenge_method),
                    request=request
                )

            if not self.validate_code_challenge(challenge,
                                                challenge_method,
                                                request.code_verifier):
                log.debug('request provided a invalid code_verifier.')
                raise errors.InvalidGrantError(request=request)
        elif self.request_validator.is_pkce_required(request.client_id, request) is True:
            if request.code_verifier is None:
                raise errors.MissingCodeVerifierError(request=request)
            raise errors.InvalidGrantError(request=request, description="Challenge not found")

        for attr in ('user', 'scopes'):
            if getattr(request, attr, None) is None:
                log.debug('request.%s was not set on code validation.', attr)

        # REQUIRED, if the "redirect_uri" parameter was included in the
        # authorization request as described in Section 4.1.1, and their
        # values MUST be identical.
        if request.redirect_uri is None:
            request.using_default_redirect_uri = True
            request.redirect_uri = self.request_validator.get_default_redirect_uri(
                request.client_id, request)
            log.debug('Using default redirect_uri %s.', request.redirect_uri)
            if not request.redirect_uri:
                raise errors.MissingRedirectURIError(request=request)