Validate Authorization Parameters

Ensures that `response_type`, `redirect_uri`, and `client_id` are included in
request parameters, and that `response_type` is supported.
326560
function validateAuthorizationParams (req, res, next) {
  var params = req.connectParams

  // missing response type
  if (!params.response_type || !params.response_type.trim()) {
    return next(new AuthorizationError({
      error: 'invalid_request',
      error_description: 'Missing response type',
      redirect_uri: params.redirect_uri,
      statusCode: 302
    }))
  }

  var responseTypes = params.response_type.trim().split(' ')

  // Check that
  // - All response_types are valid
  // - If `none` response_type is given, that it is the only response_type
  var isValidResponseType = responseTypes.indexOf('none') !== -1
    ? responseTypes.length === 1
    : responseTypes.every(
      function (responseType) {
        return validResponseTypes.indexOf(responseType) !== -1
      }
    )

  // invalid response type
  if (!isValidResponseType) {
    return next(new AuthorizationError({
      error: 'unsupported_response_type',
      error_description: 'Unsupported response type',
      redirect_uri: params.redirect_uri,
      statusCode: 302
    }))
  }

  // Check that there is at least one defined set of response_types that are
  // supported together in both the settings and on the client.
  //
  // For example, if the settings allow 'code', 'id_token token', and
  // 'code id_token token', then:
  //
  // - 'code' will pass
  // - 'id_token token' will pass
  // - 'code token id_token' will pass
  // - 'token' will NOT pass
  // - 'id_token code' will NOT pass

  // Get the registered response_type sets off the client
  var registeredResponseTypeSets =

    // If the client exists and has response_types defined
    (req.client && Array.isArray(req.client.response_types))

      // Return an array of response_type sets
      ? req.client.response_types.map(function (responseTypeString) {
        return responseTypeString.trim().split(' ')
      })
      // Otherwise, return an array with the default set, [ 'code' ]
      : [ [ 'code' ] ]

  // In the array of response_types in the settings...
  var isSupportedResponseType = settings.response_types_supported

    // check each set until we find one that satisfies the following:
    .some(function (responseTypeString) {
      var responseTypeSet = responseTypeString.split(' ')

      // if there is at least one response_type set registered on the client...
      if (registeredResponseTypeSets.some(function (regResTypeSet) {
        var indices = []

        // that has the same number of response_types in it...
        return regResTypeSet.length === responseTypeSet.length &&
          regResTypeSet.every(function (responseType) {
            var index = responseTypeSet.indexOf(responseType)

            // of which there are no duplicates...
            if (indices.indexOf(index) !== -1) {
              return false
            }
            indices.push(index)

            // and where every response_type value exists in the response_type
            // set from the settings...
            return responseTypeSet.indexOf(responseType) !== -1
          })

      // then we have found a response_type set that is both permitted by the
      // server settings and registered for the current client
      })) {
        var indices = []

        // then we check to see that the response_type set received in the auth
        // request also has the same number of response_types...
        return responseTypes.length === responseTypeSet.length &&
          responseTypes.every(function (responseType) {
            var index = responseTypeSet.indexOf(responseType)

            // that there are no duplicates...
            if (indices.indexOf(index) !== -1) {
              return false
            }
            indices.push(index)

            // and that every response_type value exists in the response_type
            // set that we verified is both registered by the client and
            // permitted by the settings

            // if this is true, then we found a match, and the response_type
            // requested is valid, permitted, and registered
            return responseTypeSet.indexOf(responseType) !== -1
          })
      } else {
        // otherwise, continue on to the next response_type in the settings
        return false
      }
    })

  // unsupported response type
  if (!isSupportedResponseType) {
    return next(new AuthorizationError({
      error: 'unsupported_response_type',
      error_description: 'Unsupported response type',
      redirect_uri: params.redirect_uri,
      statusCode: 302
    }))
  }

  // unsupported response mode
  if (params.response_mode && params.response_mode.trim() &&
    validResponseModes.indexOf(params.response_mode.trim()) === -1) {
    return next(new AuthorizationError({
      error: 'unsupported_response_mode',
      error_description: 'Unsupported response mode',
      redirect_uri: params.redirect_uri,
      statusCode: 302
    }))
  }

  // missing scope
  if (!params.scope) {
    return next(new AuthorizationError({
      error: 'invalid_scope',
      error_description: 'Missing scope',
      redirect_uri: params.redirect_uri,
      statusCode: 302
    }))
  }

  // missing openid scope
  if (params.scope.indexOf('openid') === -1) {
    return next(new AuthorizationError({
      error: 'invalid_scope',
      error_description: 'Missing openid scope',
      redirect_uri: params.redirect_uri,
      statusCode: 302
    }))
  }

  // missing nonce
  if (!params.nonce && requiresNonce(responseTypes)) {
    return next(new AuthorizationError({
      error: 'invalid_request',
      error_description: 'Missing nonce',
      redirect_uri: params.redirect_uri,
      statusCode: 302
    }))
  }

  next()
}
1287035
def _verify_client_authentication(self, request_body, http_headers=None):
        # type (str, Optional[Mapping[str, str]] -> Mapping[str, str]
        
        if http_headers is None:
            http_headers = {}
        token_request = dict(parse_qsl(request_body))
        token_request['client_id']  = verify_client_authentication(self.clients, token_request, http_headers.get('Authorization'))
        return token_request
1366820
def get_auth_uri(auth_service, client_id, scope, redirect_uri, response_type,
                 state, access_type, approval_prompt):
  """"""
  errors = []
  if response_type not in VALID_RESPONSE_TYPES:
    errors.append(
        '{0} is not a valid response_type, must be {1}.'.format(
        response_type, VALID_RESPONSE_TYPES))
  if not client_id:
    errors.append('client_id is missing or empty.')
  if not redirect_uri:
    errors.append('redirect_uri is missing or empty.')
  if not scope:
    errors.append('scope is missing or empty.')
  if access_type not in VALID_ACCESS_TYPES:
    errors.append('access_type is invalid.')
  if approval_prompt not in VALID_APPROVAL_PROMPTS:
    errors.append('approval_prompt is invalid')
  if errors:
    raise ValueError('Invalid parameters: {0}'.format('\n'.join(errors)))
  params = {
      'response_type': response_type,
      'client_id': client_id,
      'redirect_uri': redirect_uri,
      'scope': scope,
      'access_type': access_type,
      'approval_prompt': approval_prompt,
      'state': state,
  }
  return '?'.join([auth_service, urllib.urlencode(params)])
1106727
def _validate_auth_scheme(self, req):
        

        if not req.auth:
            raise AuthRequired(**{
                'detail': 'You must first login to access the requested '
                          'resource(s). Please retry your request using '
                          'OAuth 2.0 Bearer Token Authentication as '
                          'documented in RFC 6750. If you do not have an '
                          'access_token then request one at the token '
                          'endpdoint of: %s' % self.token_endpoint,
                'headers': self._error_headers,
                'links': 'tools.ietf.org/html/rfc6750#section-2.1',
            })
        elif req.auth_scheme != 'bearer':
            raise AuthRequired(**{
                'detail': 'Your Authorization header is using an unsupported '
                          'authentication scheme. Please modify your scheme '
                          'to be a string of: "Bearer".',
                'headers': self._error_headers,
                'links': 'tools.ietf.org/html/rfc6750#section-2.1',
            })
838796
def check_authorization(method, path, params)
      if authorization_failure_exception = @rights.is_request_forbidden_and_why?(method, path, params)
        Puppet.warning(_("Denying access: %{authorization_failure_exception}") % { authorization_failure_exception: authorization_failure_exception })
        raise authorization_failure_exception
      end
    end
947923
def authorize_url(self, client_id, redirect_uri, scope, state=None):
        """"""
        params = [
            ('client_id', client_id),
            ('redirect_uri', redirect_uri),
            ('scope', scope)
        ]
        if state:
            params.append(('state', state))
        return "%s?%s" % (CreateSend.oauth_uri, urlencode(params))
1141658
def __verify_auth_params(username, password, access_token):
        """"""

        if all(v is not None for v in [username, password, access_token]):
            raise ValueError('Cannot supply a username/password and a access token')

        if (username is None or password is None) and access_token is None:
            raise ValueError('Must supply a username/password or access token')
393186
def auth_url(self, scope):
        """"""
        params = {
            'response_type': 'code',
            'client_id': self.__client_id,
            'redirect_uri': self.__redirect_uri,
            'scope': scope
        }

        if self.__state is not None:
            params['state'] = self.__state

        return settings.AUTH_ENDPOINT + '/authorize?' + urllib.urlencode(params)
653726
def add_redirect_uris(request_args, service=None, **kwargs):
    
    _context = service.service_context
    if "redirect_uris" not in request_args:
        # Callbacks is a dictionary with callback type 'code', 'implicit',
        # 'form_post' as keys.
        try:
            _cbs = _context.callbacks
        except AttributeError:
            request_args['redirect_uris'] = _context.redirect_uris
        else:
            # Filter out local additions.
            _uris = [v for k, v in _cbs.items() if not k.startswith('__')]
            request_args['redirect_uris'] = _uris

    return request_args, {}
772399
function request(req) {
        var clientID = getParam(req, 'client_id')
            , redirectURI = getParam(req, 'redirect_uri')
            , scope = getParam(req, 'scope')
            , state = getParam(req, 'state');

        if (!clientID) {
            throw new AuthorizationError('Missing required parameter: client_id', 'invalid_request');
        }

        if (scope) {
            for (var i = 0, len = separators.length; i < len; i++) {
                var separated = scope.split(separators[i]);
                // only separate on the first matching separator.  this allows for a sort
                // of separator "priority" (ie, favor spaces then fallback to commas)
                if (separated.length > 1) {
                    scope = separated;
                    break;
                }
            }

            if (!Array.isArray(scope)) {
                scope = [scope];
            }
        }

        return {
            clientID: clientID,
            redirectURI: redirectURI,
            scope: scope,
            state: state
        };
    }
6321
function(req, res) {
    var params = URL.parse(req.url, true).query
      , code = params.code
      , state = params.state
    ;

    if(!code) {
      res.writeHead(400, {'Content-Type': 'text/plain'});
      return res.end('The "code" parameter is missing.');
    }
    if(!state) {
      res.writeHead(400, {'Content-Type': 'text/plain'});
      return res.end('The "state" parameter is missing.');
    }
    try {
      state = this.serializer.parse(state);
    } catch(err) {
      res.writeHead(400, {'Content-Type': 'text/plain'});
      return res.end('The "state" parameter is invalid.');
    }
    var data = {
      oauth2_server_id: state[0]
      , next_url: state[1]
      , state: state[2]
    }
    var methods = this.methods[data.oauth2_server_id];
    methods.valid_grant(data, code, function(err, token) {
      if (err) return server_error(res, err);
      if(!token) {
        res.writeHead(400, {'Content-Type': 'text/plain'});
        res.end('Invalid grant.');
        return;
      }
      data.token = token;
      methods.treat_access_token(data, req, res, function() {
        redirect(res, data.next_url);
      }, function(err){server_error(res, err)});
    });
  }
1112106
def authorized(resp, remote):
    
    if resp and 'error' in resp:
        if resp['error'] == 'bad_verification_code':
            # See https://developer.github.com/v3/oauth/#bad-verification-code
            # which recommends starting auth flow again.
            return redirect(url_for('invenio_oauthclient.login',
                                    remote_app='github'))
        elif resp['error'] in ['incorrect_client_credentials',
                               'redirect_uri_mismatch']:
            raise OAuthResponseError(
                'Application mis-configuration in GitHub', remote, resp
            )

    return authorized_signup_handler(resp, remote)
1215952
function validCorsPreflight(request) {
  if (request.method === 'OPTIONS' && request.headers.has('access-control-request-headers')) {
    return request.headers.get('access-control-request-headers').split(',').map(function (header) {
      return header.trim();
    }).includes('authorization');
  } else {
    return false;
  }
}
649872
def normalized_request_params
      query_params + protocol_params.reject { |k,v| %w(realm oauth_signature).include?(k) }.to_a + entity_params
    end
647788
def is_suitable(self, request):
        
        if self.key_type:
            validation = KEY_TYPE_VALIDATIONS.get( self.get_type() )
            return validation( request ) if validation else None
        return True
987618
def authenticate_redirect(self, callback_uri=None, cancel_uri=None,
                              extended_permissions=None, callback=None):
        
        self.require_setting(self._CLIENT_ID_SETTING, self._API_NAME)

        scope = self._BASE_SCOPE
        if extended_permissions:
            scope += extended_permissions

        args = {'client_id': self.settings[self._CLIENT_ID_SETTING],
                'redirect_uri': self.oauth2_redirect_uri(callback_uri),
                'scope': ','.join(scope)}

        # If cookie_secret is set, use it for GitHub's state value
        if not self.state and 'cookie_secret' in self.settings:
            sha1 = hashlib.sha1(self.settings['cookie_secret'])
            self.state = str(sha1.hexdigest())

        # If state is set, add it to args
        if self.state:
            args['state'] = self.state

        LOGGER.info('Redirect args: %r', args)

        # Redirect the user to the proper URL
        self.redirect(self._OAUTH_AUTHORIZE_URL +
                      auth.urllib_parse.urlencode(args))
        callback()
597749
def _validate_parameters(self):
        
        if not compatibility.is_string(self.parameters['hostname']):
            raise AMQPInvalidArgument('hostname should be a string')
        elif not compatibility.is_integer(self.parameters['port']):
            raise AMQPInvalidArgument('port should be an integer')
        elif not compatibility.is_string(self.parameters['username']):
            raise AMQPInvalidArgument('username should be a string')
        elif not compatibility.is_string(self.parameters['password']):
            raise AMQPInvalidArgument('password should be a string')
        elif not compatibility.is_string(self.parameters['virtual_host']):
            raise AMQPInvalidArgument('virtual_host should be a string')
        elif not isinstance(self.parameters['timeout'], (int, float)):
            raise AMQPInvalidArgument('timeout should be an integer or float')
        elif not compatibility.is_integer(self.parameters['heartbeat']):
            raise AMQPInvalidArgument('heartbeat should be an integer')