Use this API when you have permission to have your call act as the end client's ID.

Your calls will get 403 errors if you do not have this permission.  it is a special setup, rarely given.

@param apiVersion
@param req
@return
@throws CadiException
11958
public Rcli<CLIENT> clientAs(String apiVersion, ServletRequest req) throws CadiException {
		Rcli<CLIENT> cl = client(apiVersion);
		return cl.forUser(transferSS(((HttpServletRequest)req).getUserPrincipal()));
	}
962731
public ProviderAuthenticationResult handleAuthorizationCode(HttpServletRequest req,
            HttpServletResponse res,
            String authzCode,
            String responseState,
            ConvergedClientConfig clientConfig) {

        String clientId = clientConfig.getClientId();
        OidcClientRequest oidcClientRequest = (OidcClientRequest) req.getAttribute(ClientConstants.ATTRIB_OIDC_CLIENT_REQUEST);
        ProviderAuthenticationResult oidcResult = null;
        oidcResult = authenticatorUtil.verifyResponseState(req, res, responseState, clientConfig);
        if (oidcResult != null) {
            return oidcResult; // only if something bad happened, otherwise proceed to exchange auth code for tokens.
        }
        if (!OIDCClientAuthenticatorUtil.checkHttpsRequirement(clientConfig, clientConfig.getTokenEndpointUrl())) {
            Tr.error(tc, "OIDC_CLIENT_URL_PROTOCOL_NOT_HTTPS", clientConfig.getTokenEndpointUrl());
            oidcResult = new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
            return oidcResult;
        }
        String redirect_url = authenticatorUtil.setRedirectUrlIfNotDefined(req, clientConfig);
        if (!OIDCClientAuthenticatorUtil.checkHttpsRequirement(clientConfig, redirect_url)) {
            Tr.error(tc, "OIDC_CLIENT_URL_PROTOCOL_NOT_HTTPS", redirect_url);
            oidcResult = new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
            return oidcResult;
        }

        SSLSocketFactory sslSocketFactory = null;
        try {
            sslSocketFactory = getSSLSocketFactory(clientConfig.getTokenEndpointUrl(), clientConfig.getSSLConfigurationName(), clientId);
        } catch (SSLException e) {
            Tr.error(tc, "OIDC_CLIENT_HTTPS_WITH_SSLCONTEXT_NULL", new Object[] { e.getMessage() != null ? e.getMessage() : "invalid ssl context", clientConfig.getClientId() });
            return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
        }

        // go get the tokens and validate them.
        try {

            String url = clientConfig.getTokenEndpointUrl();
            if (url == null || url.length() == 0) {
                throw new MalformedURLException("MalformedURLException");
            }
            HashMap<String, String> tokens = oidcClientUtil.getTokensFromAuthzCode(url,
                    clientId,
                    clientConfig.getClientSecret(),
                    redirect_url,
                    authzCode,
                    clientConfig.getGrantType(),
                    sslSocketFactory,
                    clientConfig.isHostNameVerificationEnabled(),
                    clientConfig.getTokenEndpointAuthMethod(),
                    OIDCClientAuthenticatorUtil.getResources(clientConfig),
                    clientConfig.getTokenRequestParams(),
                    clientConfig.getUseSystemPropertiesForHttpClientConnections());

            oidcClientRequest.setTokenType(ClientConstants.TYPE_ID_TOKEN);

            // this has a LOT of dependencies.
            oidcResult = jose4jUtil.createResultWithJose4J(responseState, tokens, clientConfig, oidcClientRequest);

            //if tokens were valid, go get the userinfo if configured to do so, and update the authentication result to include it.
            UserInfoHelper uih = new UserInfoHelper(clientConfig);
            if (uih.willRetrieveUserInfo()) {
                OidcTokenImplBase idToken = null;
                if (oidcResult.getCustomProperties() != null) {
                    idToken = (OidcTokenImplBase) oidcResult.getCustomProperties().get(Constants.ID_TOKEN_OBJECT);
                }
                String subjFromIdToken = null;
                if (idToken != null) {
                    subjFromIdToken = idToken.getSubject();
                }
                if (subjFromIdToken != null) {
                    uih.getUserInfo(oidcResult, sslSocketFactory, tokens.get(Constants.ACCESS_TOKEN), subjFromIdToken);
                }
            }

        } catch (BadPostRequestException e) {
            Tr.error(tc, "OIDC_CLIENT_TOKEN_REQUEST_FAILURE", new Object[] { e.getErrorMessage(), clientId, clientConfig.getTokenEndpointUrl() });
            sendErrorJSON(res, e.getStatusCode(), "invalid_request", e.getErrorMessage());
            oidcResult = new ProviderAuthenticationResult(AuthResult.FAILURE, e.getStatusCode());
        } catch (Exception e) {
            Tr.error(tc, "OIDC_CLIENT_TOKEN_REQUEST_FAILURE", new Object[] { e.getLocalizedMessage(), clientId, clientConfig.getTokenEndpointUrl() });
            oidcResult = new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
        }
        return oidcResult;
    }
1123794
public boolean blockingUpdateClientApp(HttpRequest req, String clientId) throws OAuthException {
        String contentType = req.headers().get(HttpHeaderNames.CONTENT_TYPE);
        if (contentType != null && contentType.contains(ResponseBuilder.APPLICATION_JSON)) {
//            String LOCAL_NODE_ID = getBasicAuthorizationClientId(req);
//            if (LOCAL_NODE_ID == null) {
//                throw new OAuthException(ResponseBuilder.INVALID_CLIENT_ID, HttpResponseStatus.BAD_REQUEST);
//            }
            if (!isExistingClient(clientId).blockingGet()) {
                throw new OAuthException(ResponseBuilder.INVALID_CLIENT_ID, HttpResponseStatus.BAD_REQUEST);
            }
            ApplicationInfo appInfo;
            try {
                FullHttpRequest fullHttpRequest = (FullHttpRequest) req;
                appInfo = InputValidator.validate(fullHttpRequest.content().toString(CharsetUtil.UTF_8), ApplicationInfo.class);
                if (appInfo.validForUpdate()) {
                    if (appInfo.getScope() != null) {
                        String[] scopeList = appInfo.getScope().split(" ");
                        for (String s : scopeList) {
                            if (db.findScope(s).blockingGet() == null) {
                                throw new OAuthException(ResponseBuilder.SCOPE_NOT_EXIST, HttpResponseStatus.BAD_REQUEST);
                            }
                        }
                    }
                    db.updateClientCredentials(clientId, appInfo.getScope(), appInfo.getDescription(), appInfo.getStatus(),
                            appInfo.getApplicationDetails()).blockingGet();
                } else {
                    throw new OAuthException(ResponseBuilder.UPDATE_APP_MANDATORY_PARAM_MISSING, HttpResponseStatus.BAD_REQUEST);
                }
            } catch (Throwable e) {
                LOG.error("cannot update client application", e);
                throw new OAuthException(e, ResponseBuilder.CANNOT_UPDATE_APP, HttpResponseStatus.BAD_REQUEST);
            }
        } else {
            throw new OAuthException(ResponseBuilder.UNSUPPORTED_MEDIA_TYPE, HttpResponseStatus.BAD_REQUEST);
        }
        return true;
    }
348751
public com.google.appengine.v1.CreateVersionRequest getRequest() {
    return request_ == null ? com.google.appengine.v1.CreateVersionRequest.getDefaultInstance() : request_;
  }
564743
protected Api getApi(String id) throws IOException {
        Get get = new Get.Builder(getIndexName(), id).type("api").build(); //$NON-NLS-1$
        JestResult result = getClient().execute(get);
        if (result.isSucceeded()) {
            Api api = result.getSourceAsObject(Api.class);
            return api;
        } else {
            return null;
        }
    }
1192382
private String getApiIndex(String orgId, String apiId, String version) {
        return "API::" + orgId + "|" + apiId + "|" + version; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    }
717919
public static Request registerRequest(Request req) {
    assert req.supportedVersions().length > 0;
    for (API_VERSION ver : req.supportedVersions()) {
      String href = req.href(ver);
      assert (! _requests.containsKey(href)) : "Request with href "+href+" already registered";
      _requests.put(href,req);
      req.registered(ver);
    }
    return req;
  }
781944
function (req, callback) {
    var authorization = req.headers.authorization.split(' ')
    var scheme = authorization[0]
    var credentials = Buffer.from(authorization[1], 'base64')
      .toString('ascii')
      .split(':')
    var clientId = credentials[0]
    var clientSecret = credentials[1]

    // malformed credentials
    if (credentials.length !== 2) {
      return callback(new AuthorizationError({
        error: 'unauthorized_client',
        error_description: 'Malformed HTTP Basic credentials',
        statusCode: 400
      }))
    }

    // invalid authorization scheme
    if (!/^Basic$/i.test(scheme)) {
      return callback(new AuthorizationError({
        error: 'unauthorized_client',
        error_description: 'Invalid authorization scheme',
        statusCode: 400
      }))
    }

    // missing credentials
    if (!clientId || !clientSecret) {
      return callback(new AuthorizationError({
        error: 'unauthorized_client',
        error_description: 'Missing client credentials',
        statusCode: 400
      }))
    }

    Client.get(clientId, function (err, client) {
      if (err) { return callback(err) }

      // Unknown client
      if (!client) {
        return callback(new AuthorizationError({
          error: 'unauthorized_client',
          error_description: 'Unknown client identifier',
          statusCode: 401
        }))
      }

      // Mismatching secret
      if (client.client_secret !== clientSecret) {
        return callback(new AuthorizationError({
          error: 'unauthorized_client',
          error_description: 'Mismatching client secret',
          statusCode: 401
        }))
      }

      callback(null, client)
    })
  }
14033
function(apiId, swaggerPath) {
        return new Promise(function(resolve, reject) {
            fs.readFile(swaggerPath, function(err, data) {
                if (err) return reject(err);
                
                resolve(APIG.putRestApi({
                    restApiId: apiId,
                    body: data,
                    mode: 'overwrite'
                }).promise());
            });
        });
    }
327384
protected HttpAction redirectToIdentityProvider(final C context, final List<Client> currentClients) {
        final IndirectClient currentClient = (IndirectClient) currentClients.get(0);
        return (HttpAction) currentClient.redirect(context).get();
    }
330414
protected void processLegacyRequest(HyperionContext hyperionContext)
    {
        EndpointRequest request = hyperionContext.getEndpointRequest();
        EndpointResponse response = hyperionContext.getEndpointResponse();

        ApiVersionPlugin<ApiObject<Serializable>,PersistentObject<Serializable>,Serializable> apiVersionPlugin = hyperionContext.getVersionPlugin();
        EntityPlugin plugin = hyperionContext.getEntityPlugin();

        PersistenceContext persistenceContext = buildPersistenceContext(hyperionContext);

        Set<String> fieldSet = persistenceContext.getRequestedFields();
        if(fieldSet != null)
            fieldSet.add("id");

        RequestContext<ApiObject<Serializable>> requestContext = null;
        try
        {
            requestContext = marshaller.unmarshallWithContext(request.getInputStream(), apiVersionPlugin.getApiClass());
        }
        catch (MarshallingException e)
        {
            throw new BadRequestException(messageSource.getErrorMessage(ERROR_READING_REQUEST, hyperionContext.getLocale(),
                    e.getMessage()),e);
        }
        ApiObject clientObject = requestContext.getRequestObject();

        List<Serializable> ids = convertIds(hyperionContext, plugin);
        if(ids.size() != 1)
            throw new BadRequestException(messageSource.getErrorMessage(ERROR_SINGLE_ID_REQUIRED,hyperionContext.getLocale()));

        persistenceContext.setProvidedFields(requestContext.getProvidedFields());

        ApiObject saved = (ApiObject) plugin.getPersistenceOperations().updateItems(
                Collections.singletonList(clientObject),
                persistenceContext).get(0);

        processChangeEvents(hyperionContext,persistenceContext);

        response.setResponseCode(200);
        hyperionContext.setResult(saved);
    }
141208
protected ClientVersionBean getClientVersionInternal(String organizationId, String clientId, String version,
            boolean hasPermission) {
        try {
            storage.beginTx();
            ClientVersionBean clientVersion = storage.getClientVersion(organizationId, clientId, version);
            if (clientVersion == null) {
                throw ExceptionFactory.clientVersionNotFoundException(clientId, version);
            }
            // Hide some data if the user doesn't have the clientView permission
            if (!hasPermission) {
                clientVersion.setApikey(null);
            }
            storage.commitTx();
            log.debug(String.format("Got new client version %s: %s", clientVersion.getClient().getName(), clientVersion)); //$NON-NLS-1$
            return clientVersion;
        } catch (AbstractRestException e) {
            storage.rollbackTx();
            throw e;
        } catch (Exception e) {
            storage.rollbackTx();
            throw new SystemErrorException(e);
        }
    }
1167799
def execute_api_request(self):
        
        if not self.auth.check_auth():
            raise Exception('Authentification needed or API not available with your type of connection')
        if self.auth.is_authentified():
            id_cookie = {BboxConstant.COOKIE_BBOX_ID: self.auth.get_cookie_id()}
            if self.parameters is None:
                resp = self.call_method(self.api_url.get_url(), cookies=id_cookie)
            else:
                resp = self.call_method(self.api_url.get_url(),
                                        data=self.parameters, cookies=id_cookie)
        else:
            if self.parameters is None:
                resp = self.call_method(self.api_url.get_url())
            else:
                resp = self.call_method(self.api_url.get_url(),
                                        data=self.parameters)
        if resp.status_code != 200:
            # This means something went wrong.
            raise Exception('Error {} with request {}'.format(
                resp.status_code, self.api_url.get_url()))

        return resp
312099
public ApiResponse<UserEnvelope> getSelfWithHttpInfo() throws ApiException {
        com.squareup.okhttp.Call call = getSelfValidateBeforeCall(null, null);
        Type localVarReturnType = new TypeToken<UserEnvelope>(){}.getType();
        return apiClient.execute(call, localVarReturnType);
    }
834530
def _api_query(self, protection=None, path_dict=None, options=None):
        

        if not options:
            options = {}

        if self.api_version not in path_dict:
            raise Exception('method call not available under API version {}'.format(self.api_version))

        request_url = BASE_URL_V2_0 if self.api_version == API_V2_0 else BASE_URL_V1_1
        request_url = request_url.format(path=path_dict[self.api_version])

        nonce = str(int(time.time() * 1000))

        if protection != PROTECTION_PUB:
            request_url = "{0}apikey={1}&nonce={2}&".format(request_url, self.api_key, nonce)

        request_url += urlencode(options)

        try:
            if sys.version_info >= (3, 0) and protection != PROTECTION_PUB:

                apisign = hmac.new(bytearray(self.api_secret, 'ascii'),
                                   bytearray(request_url, 'ascii'),
                                   hashlib.sha512).hexdigest()

            else:

                apisign = hmac.new(self.api_secret.encode(),
                                   request_url.encode(),
                                   hashlib.sha512).hexdigest()

            self.wait()

            return self.dispatch(request_url, apisign)

        except Exception:
            return {
                'success': False,
                'message': 'NO_API_RESPONSE',
                'result': None
            }
535425
protected Api getApiInternal(String organizationId, String apiId, String apiVersion) throws SQLException {
        QueryRunner run = new QueryRunner(ds);
        return run.query("SELECT bean FROM gw_apis WHERE org_id = ? AND id = ? AND version = ?", //$NON-NLS-1$
                Handlers.API_HANDLER, organizationId, apiId, apiVersion);
    }
359833
public Response api(Request request) throws IOException {
    Request req = new Request();
    req.setMethod(request.getMethod());
    req.setBaseUri(this.host);
    req.setEndpoint("/" + version + "/" + request.getEndpoint());
    req.setBody(request.getBody());
    for (Map.Entry<String, String> header : this.requestHeaders.entrySet()) {
      req.addHeader(header.getKey(), header.getValue());
    }
    for (Map.Entry<String, String> queryParam : request.getQueryParams().entrySet()) {
      req.addQueryParam(queryParam.getKey(), queryParam.getValue());
    }

    return makeCall(req);
  }