Esempio n. 1
0
    def validate_token_request(self, request):
        # We need to set these at None by default otherwise
        # we are going to get some AttributeError later
        request._params.setdefault("backend", None)
        request._params.setdefault("client_secret", None)

        if request.grant_type != 'convert_token':
            raise errors.UnsupportedGrantTypeError(request=request)

        # We check that a token parameter is present.
        # It should contain the social token to be used with the backend
        if request.token is None:
            raise errors.InvalidRequestError(
                description='Missing token parameter.', request=request)

        # We check that a provider parameter is present.
        # It should contain the name of the social provider to be used
        if request.provider is None:
            raise errors.InvalidRequestError(
                description='Missing provider parameter.', request=request)

        if not request.client_id:
            raise errors.MissingClientIdError(request=request)

        if not self.request_validator.validate_client_id(
                request.client_id, request):
            raise errors.InvalidClientIdError(request=request)

        # Existing code to retrieve the application instance from the client id
        if self.request_validator.client_authentication_required(request):
            logger.debug('Authenticating client, %r.', request)
            if not self.request_validator.authenticate_client(request):
                logger.debug('Invalid client (%r), denying access.', request)
                raise errors.InvalidClientError(request=request)
        elif not self.request_validator.authenticate_client_id(
                request.client_id, request):
            logger.debug('Client authentication failed, %r.', request)
            raise errors.InvalidClientError(request=request)

        # Ensure client is authorized use of this grant type
        # We chose refresh_token as a grant_type
        # as we don't want to modify all the codebase.
        # It is also the most permissive and logical grant for our needs.
        request.grant_type = "refresh_token"
        self.validate_grant_type(request)
        self.validate_scopes(request)

        # TODO: Implement logic to decide whether or not to grant the access_token
        # Decoded body is a list of tuple, dict is better
        body = {}
        for t in request.decoded_body:
            body[t[0]] = t[1]

        user = get_user_by_access_token(token=body['token'],
                                        provider=body['provider'],
                                        nonce=body['nonce'])
        if user is None:
            raise errors.InvalidClientError(
                "Authentication token for the given provider is invalid")
        request.user = user
Esempio n. 2
0
    def validate_client(self, request):
        if not request.client_id:
            raise errors.MissingClientIdError(state=request.state,
                                              request=request)

        if not self.request_validator.validate_client_id(
                request.client_id, request):
            raise errors.InvalidClientIdError(state=request.state,
                                              request=request)
Esempio n. 3
0
    def validate_authorization_request(self, request):
        """
        Same as original method (of AuthorizationCodeGrant) except for
        letting out the request_uri and request_uri validations
        :param request:
        :return:
        """
        for param in ('client_id', 'response_type', 'scope', 'state'):
            try:
                duplicate_params = request.duplicate_params
            except ValueError:
                raise errors.InvalidRequestFatalError(description='Unable to parse query string', request=request)
            if param in duplicate_params:
                raise errors.InvalidRequestFatalError(description='Duplicate %s parameter.' % param, request=request)

        if not request.client_id:
            raise errors.MissingClientIdError(request=request)

        if not self.request_validator.validate_client_id(request.client_id, request):
            raise errors.InvalidClientIdError(request=request)

        if request.response_type is None:
            raise errors.MissingResponseTypeError(request=request)
        elif request.response_type not in self.response_types:
            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)

        self.validate_scopes(request)

        return request.scopes, {
            'client_id': request.client_id,
            'response_type': request.response_type,
            'state': request.state,
            'request': request,
            'redirect_uri': ''
        }
Esempio n. 4
0
    def validate_token_request(self, request):
        # This method's code is based on the parent method's code
        # We removed the original comments to replace with ours
        # explaining our modifications.

        # We need to set these at None by default otherwise
        # we are going to get some AttributeError later
        request._params.setdefault("backend", None)
        request._params.setdefault("client_secret", None)

        if request.grant_type != 'convert_token':
            raise errors.UnsupportedGrantTypeError(request=request)

        # We check that a token parameter is present.
        # It should contain the social token to be used with the backend
        if request.token is None:
            raise errors.InvalidRequestError(
                description='Missing token parameter.', request=request)

        # We check that a backend parameter is present.
        # It should contain the name of the social backend to be used
        if request.backend is None:
            raise errors.InvalidRequestError(
                description='Missing backend parameter.', request=request)

        if not request.client_id:
            raise errors.MissingClientIdError(request=request)

        if not self.request_validator.validate_client_id(
                request.client_id, request):
            raise errors.InvalidClientIdError(request=request)

        # Existing code to retrieve the application instance from the client id
        if self.request_validator.client_authentication_required(request):
            log.debug('Authenticating client, %r.', request)
            if not self.request_validator.authenticate_client(request):
                log.debug('Invalid client (%r), denying access.', request)
                raise errors.InvalidClientError(request=request)
        elif not self.request_validator.authenticate_client_id(
                request.client_id, request):
            log.debug('Client authentication failed, %r.', request)
            raise errors.InvalidClientError(request=request)

        # Ensure client is authorized use of this grant type
        # We chose refresh_token as a grant_type
        # as we don't want to modify all the codebase.
        # It is also the most permissive and logical grant for our needs.
        request.grant_type = "refresh_token"
        self.validate_grant_type(request)

        self.validate_scopes(request)

        # TODO: Find a better way to pass the django request object
        strategy = load_strategy(request=request.django_request)

        try:
            backend = load_backend(
                strategy, request.backend,
                reverse(NAMESPACE + ":complete", args=(request.backend, )))
        except MissingBackend:
            raise errors.InvalidRequestError(
                description='Invalid backend parameter.', request=request)

        try:
            user = backend.do_auth(access_token=request.token)
        except requests.HTTPError as e:
            raise errors.InvalidRequestError(
                description="Backend responded with HTTP{0}: {1}.".format(
                    e.response.status_code, e.response.text),
                request=request)
        except SocialAuthBaseException as e:
            raise errors.AccessDeniedError(description=str(e), request=request)

        if not user:
            raise errors.InvalidGrantError('Invalid credentials given.',
                                           request=request)

        if not user.is_active:
            raise errors.InvalidGrantError('User inactive or deleted.',
                                           request=request)

        request.user = user
        log.debug('Authorizing access to user %r.', request.user)
Esempio n. 5
0
    def validate_authorization_request(self, request):
        """Check the authorization request for normal and fatal errors.

        A normal error could be a missing response_type parameter or the client
        attempting to access scope it is not allowed to ask authorization for.
        Normal errors can safely be included in the redirection URI and
        sent back to the client.

        Fatal errors occur when the client_id or redirect_uri is invalid or
        missing. These must be caught by the provider and handled, how this
        is done is outside of the scope of OAuthLib but showing an error
        page describing the issue is a good idea.

        :param request: OAuthlib request.
        :type request: oauthlib.common.Request
        """

        # First check for fatal errors

        # 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.

        # First check duplicate parameters
        for param in ('client_id', 'response_type', 'redirect_uri', 'scope',
                      'state'):
            try:
                duplicate_params = request.duplicate_params
                if param in duplicate_params:
                    raise errors.InvalidRequestFatalError(
                        description='Duplicate %s parameter.' % param,
                        request=request)
            except ValueError:
                log.exception(
                    errors.InvalidRequestFatalError(
                        description='Unable to parse query string',
                        request=request))

        # REQUIRED. The client identifier as described in Section 2.2.
        # https://tools.ietf.org/html/rfc6749#section-2.2
        if not request.client_id:
            raise errors.MissingClientIdError(request=request)

        if not self.request_validator.validate_client_id(
                request.client_id, request):
            raise errors.InvalidClientIdError(request=request)

        # OPTIONAL. As described in Section 3.1.2.
        # https://tools.ietf.org/html/rfc6749#section-3.1.2
        log.debug('Validating redirection uri %s for client %s.',
                  request.redirect_uri, request.client_id)

        # OPTIONAL. As described in Section 3.1.2.
        # https://tools.ietf.org/html/rfc6749#section-3.1.2
        self._handle_redirects(request)

        # Then check for normal errors.

        # 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

        # 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 'code' not 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:
            if request.code_challenge is None:
                raise errors.MissingCodeChallengeError(request=request)

        if request.code_challenge is not None:
            request_info["code_challenge"] = request.code_challenge

            # OPTIONAL, defaults to "plain" if not present in the request.
            if request.code_challenge_method is None:
                request.code_challenge_method = "plain"

            if request.code_challenge_method not in self._code_challenge_methods:
                raise errors.UnsupportedCodeChallengeMethodError(
                    request=request)
            request_info[
                "code_challenge_method"] = request.code_challenge_method

        # OPTIONAL. The scope of the access request as described by Section 3.3
        # https://tools.ietf.org/html/rfc6749#section-3.3
        self.validate_scopes(request)

        request_info.update({
            'client_id': request.client_id,
            'redirect_uri': request.redirect_uri,
            'response_type': request.response_type,
            'state': request.state,
            'request': request
        })

        for validator in self.custom_validators.post_auth:
            request_info.update(validator(request))

        return request.scopes, request_info
Esempio n. 6
0
    def validate_token_request(self, request):
        """Check the token request for normal and fatal errors.

        This method is very similar to validate_authorization_request in
        the AuthorizationCodeGrant but differ in a few subtle areas.

        A normal error could be a missing response_type parameter or the client
        attempting to access scope it is not allowed to ask authorization for.
        Normal errors can safely be included in the redirection URI and
        sent back to the client.

        Fatal errors occur when the client_id or redirect_uri is invalid or
        missing. These must be caught by the provider and handled, how this
        is done is outside of the scope of OAuthLib but showing an error
        page describing the issue is a good idea.
        """

        # First check for fatal errors

        # 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.

        # REQUIRED. The client identifier as described in Section 2.2.
        # http://tools.ietf.org/html/rfc6749#section-2.2
        if not request.client_id:
            raise errors.MissingClientIdError(state=request.state,
                                              request=request)

        if not self.request_validator.validate_client_id(
                request.client_id, request):
            raise errors.InvalidClientIdError(state=request.state,
                                              request=request)

        # OPTIONAL. As described in Section 3.1.2.
        # http://tools.ietf.org/html/rfc6749#section-3.1.2
        if request.redirect_uri is not None:
            request.using_default_redirect_uri = False
            log.debug('Using provided redirect_uri %s', request.redirect_uri)
            if not is_absolute_uri(request.redirect_uri):
                raise errors.InvalidRedirectURIError(state=request.state,
                                                     request=request)

            # The authorization server MUST verify that the redirection URI
            # to which it will redirect the access token matches a
            # redirection URI registered by the client as described in
            # Section 3.1.2.
            # http://tools.ietf.org/html/rfc6749#section-3.1.2
            if not self.request_validator.validate_redirect_uri(
                    request.client_id, request.redirect_uri, request):
                raise errors.MismatchingRedirectURIError(state=request.state,
                                                         request=request)
        else:
            request.redirect_uri = self.request_validator.get_default_redirect_uri(
                request.client_id, request)
            request.using_default_redirect_uri = True
            log.debug('Using default redirect_uri %s.', request.redirect_uri)
            if not request.redirect_uri:
                raise errors.MissingRedirectURIError(state=request.state,
                                                     request=request)
            if not is_absolute_uri(request.redirect_uri):
                raise errors.InvalidRedirectURIError(state=request.state,
                                                     request=request)

        # Then check for normal errors.

        # 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 fragment component of the redirection URI using the
        # "application/x-www-form-urlencoded" format, per Appendix B.
        # http://tools.ietf.org/html/rfc6749#appendix-B

        # Note that the correct parameters to be added are automatically
        # populated through the use of specific exceptions.
        if request.response_type is None:
            raise errors.InvalidRequestError(
                state=request.state,
                description='Missing response_type parameter.',
                request=request)

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

        # REQUIRED. Value MUST be set to "token".
        if request.response_type not in self.VALID_RESPONSE_TYPES:
            raise errors.UnsupportedResponseTypeError(state=request.state,
                                                      request=request)

        log.debug('Validating use of response_type token for client %r (%r).',
                  request.client_id, request.client)
        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. The scope of the access request as described by Section 3.3
        # http://tools.ietf.org/html/rfc6749#section-3.3
        self.validate_scopes(request)

        return request.scopes, {
            'client_id': request.client_id,
            'redirect_uri': request.redirect_uri,
            'response_type': request.response_type,
            'state': request.state,
            'request': request,
        }