Get the response type by its name

@throws OAuth2Exception (unsupported_grant_type) When response type is not registered
191137
public function getResponseType(string $responseType): GrantInterface
    {
        if ($this->hasResponseType($responseType)) {
            return $this->responseTypes[$responseType];
        }

        // If we reach here... then no grant was found. Not good!
        throw OAuth2Exception::unsupportedResponseType(sprintf(
            'Response type "%s" is not supported by this server',
            $responseType
        ));
    }
247426
def _get_signature_type_and_params(self, request):
        
        # Per RFC5849, only the Authorization header may contain the 'realm'
        # optional parameter.
        header_params = signature.collect_parameters(headers=request.headers,
                                                     exclude_oauth_signature=False, with_realm=True)
        body_params = signature.collect_parameters(body=request.body,
                                                   exclude_oauth_signature=False)
        query_params = signature.collect_parameters(uri_query=request.uri_query,
                                                    exclude_oauth_signature=False)

        params = []
        params.extend(header_params)
        params.extend(body_params)
        params.extend(query_params)
        signature_types_with_oauth_params = list(filter(lambda s: s[2], (
            (SIGNATURE_TYPE_AUTH_HEADER, params,
                utils.filter_oauth_params(header_params)),
            (SIGNATURE_TYPE_BODY, params,
                utils.filter_oauth_params(body_params)),
            (SIGNATURE_TYPE_QUERY, params,
                utils.filter_oauth_params(query_params))
        )))

        if len(signature_types_with_oauth_params) > 1:
            found_types = [s[0] for s in signature_types_with_oauth_params]
            raise errors.InvalidRequestError(
                description=('oauth_ params must come from only 1 signature'
                             'type but were found in %s',
                             ', '.join(found_types)))

        try:
            signature_type, params, oauth_params = signature_types_with_oauth_params[
                0]
        except IndexError:
            raise errors.InvalidRequestError(
                description='Missing mandatory OAuth parameters.')

        return signature_type, params, oauth_params
285465
def _access_token_endpoint(self, grantType, extraParams={}):
        
        response = requests.post(
            self._format_url(OAUTH2_ROOT + 'access_token'),
            data = _extend({
                'grant_type': grantType,
                'client_id': self.client.get('client_id', ''),
                'client_secret': self.client.get('client_secret', ''),
                'redirect_uri': self.client.get('redirect_uri', '')
            }, extraParams))
        
        data = response.json()
        if 'error' in data or 'error_description' in data:
            raise _token_error_from_data(data)
        else:
            return self.set_creds(data)
161498
public static boolean isAuthorizedResponseTypeForService(final J2EContext context, final OAuthRegisteredService registeredService) {
        val responseType = context.getRequestParameter(OAuth20Constants.RESPONSE_TYPE);
        if (registeredService.getSupportedResponseTypes() != null && !registeredService.getSupportedResponseTypes().isEmpty()) {
            LOGGER.debug("Checking response type [{}] against supported response types [{}]", responseType, registeredService.getSupportedResponseTypes());
            return registeredService.getSupportedResponseTypes().stream().anyMatch(s -> s.equalsIgnoreCase(responseType));
        }

        LOGGER.warn("Registered service [{}] does not define any authorized/supported response types. "
            + "It is STRONGLY recommended that you authorize and assign response types to the service definition. "
            + "While just a warning for now, this behavior will be enforced by CAS in future versions.", registeredService.getName());
        return true;
    }
745785
public String getNewToken(GrantType grantType) throws FoxHttpException, MalformedURLException {
        FoxHttpRequest request = this.generateRequestForGrantType(grantType);
        this.getOAuth2RequestExecutor().executeOAuth2Request(request, this);
        return getOAuth2Store().getAccessToken();
    }
340634
def _get_response_mime_type(self):
        
        view_name = self.request.view_name
        if view_name != '':
            mime_type = get_registered_mime_type_for_name(view_name)
        else:
            mime_type = None
            acc = None
            for acc in self.request.accept:
                if acc == '*/*':
                    # The client does not care; use the default.
                    mime_type = self.__get_default_response_mime_type()
                    break
                try:
                    mime_type = \
                            get_registered_mime_type_for_string(acc.lower())
                except KeyError:
                    pass
                else:
                    break
            if mime_type is None:
                if not acc is None:
                    # The client specified a MIME type we can not handle; this
                    # is a 406 exception. We supply allowed MIME content
                    # types in the body of the response.
                    headers = \
                        [('Location', self.request.path_url),
                         ('Content-Type', TextPlainMime.mime_type_string),
                         ]
                    mime_strings = get_registered_mime_strings()
                    exc = HTTPNotAcceptable('Requested MIME content type(s) '
                                            'not acceptable.',
                                            body=','.join(mime_strings),
                                            headers=headers)
                    raise exc
                mime_type = self.__get_default_response_mime_type()
        return mime_type
136836
def validate_grant_type(self, request):
        
        client_id = getattr(request, 'client_id', None)
        if not self.request_validator.validate_grant_type(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)
520451
public static boolean isResponseModeTypeFormPost(final OAuthRegisteredService registeredService, final OAuth20ResponseModeTypes responseType) {
        return responseType == OAuth20ResponseModeTypes.FORM_POST || StringUtils.equalsIgnoreCase("post", registeredService.getResponseType());
    }
940890
protected function getResponseType()
    {
        if ($this->responseType instanceof ResponseTypeInterface === false) {
            $this->responseType = new CustomBearerTokenResponse();
        }

        $this->responseType->setPrivateKey($this->privateKey);

        return $this->responseType;
    }
227143
public function getTokenResponse()
    {
        $query = [
            'grant_type' => 'client_credential',
            'appid' => $this['appid'],
            'secret' => $this['appsecret'],
        ];

        $response = Http::request('GET', static::ACCESS_TOKEN)
            ->withQuery($query)
            ->send();

        if ($response->containsKey('errcode')) {
            throw new \Exception($response['errmsg'], $response['errcode']);
        }

        return $response;
    }
690979
public function getAuthorizationUrl($redirect_uri, $response_type = 'code')
    {
        return sprintf('https://%s/auth/o/login/?%s',
            str_replace('api.', '', parse_url($this->adapter->getEndpoint(), PHP_URL_HOST)),
            http_build_query([
                'response_type' => $response_type,
                'client_id' => $this->adapter->getClient(),
                'redirect_uri' => $redirect_uri,
            ])
        );
    }
55041
protected function getToken()
    {
        /* @var ResponseInterface $response */
        $response = $this->post(self::TOKEN_URI, [
            'body' => [
                'grant_type' => 'authorization_code',
                'code' => $this->getCodeQueryField(),
                'client_id' => $this->clientId,
                'client_secret' => $this->clientSecret
            ]
        ]);

        if ($response->getStatusCode() == 200) {
            $this->setPropertiesBasedOnSuccessResponse($response->json());

            return;
        }

        $response = $response->json();
        throw new OAuthException("{$response['error']}:{$response['error_description']}");
    }
1218196
def _get_acceptable_response_type():
    """"""
    if ('Accept' not in request.headers or request.headers['Accept'] in
            ALL_CONTENT_TYPES):
        return JSON
    acceptable_content_types = set(
        request.headers['ACCEPT'].strip().split(','))
    if acceptable_content_types & HTML_CONTENT_TYPES:
        return HTML
    elif acceptable_content_types & JSON_CONTENT_TYPES:
        return JSON
    else:
        # HTTP 406 Not Acceptable
        raise InvalidAPIUsage(406)
819617
public function getRequestToken($callback_uri = NULL) {

    // set callback_uri
    $this->getOauthPlugin()->setCallbackUri($callback_uri);

    //Get request token
    $response = $this->get($this->getConfig('request_token_path'))->send();
    $request_token = array();
    parse_str($response->getBody(), $request_token);

    // Throw exception if the callback isn't confirmed
    if (!isset($request_token['oauth_callback_confirmed']) || !in_array($request_token['oauth_callback_confirmed'], array(true, "true"))) {
      throw new \Exception("There was an error regarding the callback confirmation");
    }

    // Return RequestToken
    return $request_token;
  }
534562
public function getHeaders($names = []) {
        if (is_string($names)) {
            $names = [$names];
        }
        elseif (is_array($names)) {
            foreach ($names as $name) {
                if (!is_string($name)) throw new IllegalTypeException('Illegal argument type in argument $names: '.gettype($name));
            }
        }
        else throw new IllegalTypeException('Illegal type of parameter $names: '.gettype($names));

        // read all headers once
        static $headers = null; if ($headers === null) {
            if (function_exists('apache_request_headers')) {
                $headers = apache_request_headers();
                // TODO: Apache skips REDIRECT_* headers
            }
            else {
                static $fixHeaderNames = ['CDN'=>1, 'DNT'=>2, 'X-CDN'=>3];
                $headers = [];
                foreach ($_SERVER as $name => $value) {
                    while (substr($name, 0, 9) == 'REDIRECT_') {
                        $name = substr($name, 9);
                        if (isset($_SERVER[$name]))
                            continue 2;
                    }
                    if (substr($name, 0, 5) == 'HTTP_') {
                        $name = substr($name, 5);
                        if (!isset($fixHeaderNames[$name]))
                            $name = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower($name))));
                        $headers[$name] = $value;
                    }
                }
            }

            if (!isset($headers['Authorization'])) {
                if (isset($_SERVER['PHP_AUTH_USER'])) {
                    $passwd = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
                    $headers['Authorization'] = 'Basic '. base64_encode($_SERVER['PHP_AUTH_USER'].':'.$passwd);
                }
                elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) {
                    $headers['Authorization'] = $_SERVER['PHP_AUTH_DIGEST'];
                }
            }
        }

        // return all or just the specified headers
        if (!$names)
            return $headers;
        return \array_intersect_ukey($headers, \array_flip($names), 'strCaseCmp');
    }
513720
private function getResponseType()
    {
        if (false === strpos($this->url, '.')) {
            return "";
        }
        list($path, $type) = explode('.', basename($this->url), 2);

        return $type;
    }
1250647
protected function getAccessToken()
    {
        switch ($this->grant) {
            case 'provided_token':
                return $this->token;

            case 'client_credentials':
                return $this->getFrameworkBridge()->getClientToken();

            case 'authorization_code':
                $user = $this->getFrameworkBridge()->getCurrentUser();

                if (! $user) {
                    return null;
                }

                return $user->getOAuthToken();

            default:
                throw new \Exception('Unsupported grant type. Check $this->grant.');
        }
    }