issue a new clientCredentials

@param req http request
@return ClientCredentials
@throws OAuthException OAuthException
497068
public Single<ClientCredentials> issueClientCredentials(HttpRequest req) throws OAuthException {
        Single<ClientCredentials> creds;
        String contentType = req.headers().get(HttpHeaderNames.CONTENT_TYPE);

        if (contentType != null && contentType.contains(HttpHeaderValues.APPLICATION_JSON)) {
            ApplicationInfo appInfo;
            FullHttpRequest fullHttpRequest = (FullHttpRequest) req;
            appInfo = InputValidator.validate(fullHttpRequest.content().toString(CharsetUtil.UTF_8), ApplicationInfo.class);
            if (appInfo.valid()) {
                String[] scopeList = appInfo.getScope().split(SCOPE_SPLITTER);
                creds = db.getAllScopes().flatMap(allScopes -> {
                    for (String s : scopeList) {
                        if (matchScope(allScopes, s) == null) {
                            throw new OAuthException(ResponseBuilder.SCOPE_NOT_EXIST, HttpResponseStatus.BAD_REQUEST);
                        }
                    }
                    // check client_id, client_secret passed
                    if ((appInfo.getId() != null && appInfo.getId().length() > 0) && (appInfo.getSecret() != null && appInfo.getSecret().length() > 0)) {
                        // check if passed client_id, client_secret are valid
                        if (areClientCredentialsValid(appInfo.getId(), appInfo.getSecret())) {
                            return db.findClientCredentials(appInfo.getId())
                                    .switchIfEmpty(Single.just(new ClientCredentials(appInfo.getName(), appInfo.getScope(), appInfo.getDescription(), appInfo.getRedirectUri(), appInfo.getId(), appInfo.getSecret(), appInfo.getApplicationDetails())))
                                    .flatMap(clientCredentials -> {
                                        // if a client app with this client_id already registered
                                        return Single.error(new OAuthException(ResponseBuilder.ALREADY_REGISTERED_APP, HttpResponseStatus.BAD_REQUEST));
                                    });
                        } else {
                            throw new OAuthException(ResponseBuilder.INVALID_CLIENT_CREDENTIALS, HttpResponseStatus.BAD_REQUEST);
                        }
                    } else {
                        ClientCredentials clientCredentials = new ClientCredentials(appInfo.getName(), appInfo.getScope(), appInfo.getDescription(), appInfo.getRedirectUri(), appInfo.getApplicationDetails());
                        return Single.just(clientCredentials);
                    }
                }).flatMap(credsTmp -> db
                        .storeClientCredentials(credsTmp)
                        .andThen(Single.just(credsTmp)));
            } else {
                return Single.error(new OAuthException(ResponseBuilder.NAME_OR_SCOPE_OR_URI_IS_NULL, HttpResponseStatus.BAD_REQUEST));
            }
            // return Single.error(new OAuthException(e, ResponseBuilder.CANNOT_REGISTER_APP, HttpResponseStatus.BAD_REQUEST));
        } else {
            return Single.error(new OAuthException(ResponseBuilder.UNSUPPORTED_MEDIA_TYPE, HttpResponseStatus.BAD_REQUEST));
        }
        return creds;
    }
182752
def refresh_oauth_credential(self):
        """"""
        if self.session.token_type == auth.SERVER_TOKEN_TYPE:
            return

        credential = self.session.oauth2credential
        if credential.is_stale():
            refresh_session = refresh_access_token(credential)
            self.session = refresh_session
625589
public static Map<String, Object> createFormParamClientCredentialsGrantType(String scope) {
        Map<String, Object> formParams = new HashMap<>();
        formParams.put("grant_type", "client_credentials");
        if (scope != null) {
            formParams.put("scope", scope);
        }
        return formParams;
    }
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;
    }
1078824
public static ClientConfiguration createClient(final AuthScope authScope, final Credentials credentials) {
        return createClient(authScope, credentials, emptyList(), emptyList());
    }
461670
public function createCredentials(ClientCredentials $client)
    {
        return $this->createCommand()
            ->setRequest($this->client->post('credentials'))
            ->setBodyEntity($client, 'json')
            ->setResponseClass('Maba\OAuthCommerceInternalClient\Entity\ClientCredentials')
        ;
    }
703742
static OAuth2Credentials createOAuth2Credentials(SessionConfiguration config) throws IOException {


        return new OAuth2Credentials.Builder()
                .setCredentialDataStoreFactory(MemoryDataStoreFactory.getDefaultInstance())
                .setRedirectUri(config.getRedirectUri())
                .setScopes(config.getScopes())
                .setClientSecrets(config.getClientId(), config.getClientSecret())
                .build();
    }
755825
def authorize(credentials, client_class=Client):
    
    client = client_class(auth=credentials)
    client.login()
    return client
1140963
public AuthorizationCodeRefreshRequest.Builder authorizationCodeRefresh() {
    return new AuthorizationCodeRefreshRequest.Builder(clientId, clientSecret)
            .setDefaults(httpManager, scheme, host, port)
            .grant_type("refresh_token")
            .refresh_token(refreshToken);
  }
1225420
public static DefaultAuthenticationTransaction of(final Service service, final Credential... credentials) {
        val creds = sanitizeCredentials(credentials);
        return new DefaultAuthenticationTransaction(service, creds);
    }
362306
protected function createWebClient()
    {
        $userId = array_get($this->config, 'user_id', false);
        $licenseKey = array_get($this->config, 'license_key', false);

        // check and make sure they are set
        if (! $userId || ! $licenseKey) {
            throw new InvalidCredentialsException();
        }

        return new Client($userId, $licenseKey);
    }
81422
def oauth_client_create(self, name, redirect_uri, **kwargs):
        
        params = {
            "label": name,
            "redirect_uri": redirect_uri,
        }
        params.update(kwargs)

        result = self.client.post('/account/oauth-clients', data=params)

        if not 'id' in result:
            raise UnexpectedResponseError('Unexpected response when creating OAuth Client!',
                    json=result)

        c = OAuthClient(self.client, result['id'], result)
        return c
99411
private void getCredentials(final String code) {
        new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                try {
                    mBootstrapper.getUserCredentials(code);
                    return true;

                } catch (IOException ex) {
                    LOGGER.error("Error getting oauth credentials", ex);
                    setResult(RESULT_CANCELED);
                    finish();

                } catch (CStorageException ex) {
                    LOGGER.error("Error getting oauth credentials", ex);
                    setResult(RESULT_CANCELED);
                    finish();
                }
                // Failure
                return false;
            }

            @Override
            protected void onPostExecute(Boolean result) {
                if(result) {
                    setResult(RESULT_OK);
                } else {
                    setResult(RESULT_CANCELED);
                }
                finish();
            }
        }.execute();
    }
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;
    }
1196501
public SdkClientBuilder proxyCredentials(String user, String password) {
        this.proxyCredentials = new UsernamePasswordCredentials(user, password);
        return this;
    }
842197
function Client(name, password) {

    if (!(this instanceof Client)) {
        return new Client(name, password);
    }

    this.name = name || 'RETS-Connector1/2';
    this.password = password || '';

}
813733
public ProviderAuthenticationResult handleRedirectToServer(HttpServletRequest req, HttpServletResponse res, ConvergedClientConfig clientConfig) {
        String authorizationEndpoint = clientConfig.getAuthorizationEndpointUrl();

        if (!checkHttpsRequirement(clientConfig, authorizationEndpoint)) {
            Tr.error(tc, "OIDC_CLIENT_URL_PROTOCOL_NOT_HTTPS", authorizationEndpoint);
            return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
        }

        if (clientConfig.createSession()) {
            try {
                req.getSession(true);
            } catch (Exception e) {
                // ignore it. Session exists
            }
        }

        String strRandom = OidcUtil.generateRandom(OidcUtil.RANDOM_LENGTH);
        String timestamp = OidcUtil.getTimeStamp();
        String state = timestamp + strRandom;
        if (!req.getMethod().equalsIgnoreCase("GET") && req.getParameter("oidc_client") != null) {
            state = state + req.getParameter("oidc_client");
        }
        String cookieValue = HashUtils.createStateCookieValue(clientConfig, state);
        String cookieName = ClientConstants.WAS_OIDC_STATE_KEY + HashUtils.getStrHashCode(state);
        boolean isHttpsRequest = req.getScheme().toLowerCase().contains("https");
        int cookieLifeTime = (int) clientConfig.getAuthenticationTimeLimitInSeconds();
        Cookie cookie = OidcClientUtil.createCookie(cookieName, cookieValue, cookieLifeTime, req);
        if (clientConfig.isHttpsRequired() == true && isHttpsRequest) {
            cookie.setSecure(true);
        }
        res.addCookie(cookie);

        String redirect_url = setRedirectUrlIfNotDefined(req, clientConfig);
        if (!checkHttpsRequirement(clientConfig, redirect_url)) {
            Tr.error(tc, "OIDC_CLIENT_URL_PROTOCOL_NOT_HTTPS", redirect_url);
            return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
        }

        String acr_values = req.getParameter("acr_values");

        String authzEndPointUrlWithQuery = null;
        try {
            boolean openidScopeMissing = !clientConfig.isSocial() && !isOpenIDScopeSpecified(clientConfig); // some social media use nonstandard scope
            boolean scopeMissing = clientConfig.getScope() == null || clientConfig.getScope().length() == 0;
            if (openidScopeMissing || scopeMissing) {
                Tr.error(tc, "OIDC_CLIENT_REQUEST_MISSING_OPENID_SCOPE",
                        clientConfig.getClientId(), clientConfig.getScope()); // CWWKS1713E
                return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
            }

            authzEndPointUrlWithQuery = buildAuthorizationUrlWithQuery(req, (OidcClientRequest) req.getAttribute(ClientConstants.ATTRIB_OIDC_CLIENT_REQUEST), state, clientConfig, redirect_url, acr_values);

            // preserve post param.
            WebAppSecurityConfig webAppSecConfig = WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig();
            PostParameterHelper pph = new PostParameterHelper(webAppSecConfig);
            pph.save(req, res);
            // Redirect to OP
            // If clientSideRedirect is true (default is true) then do the
            // redirect.  If the user agent doesn't support javascript then config can set this to false.
            if (clientConfig.isClientSideRedirect()) {
                String domain = OidcClientUtil.getSsoDomain(req);
                doClientSideRedirect(res, authzEndPointUrlWithQuery, state, domain);
            } else {
                String urlCookieName = ClientConstants.WAS_REQ_URL_OIDC + HashUtils.getStrHashCode(state);
                Cookie c = OidcClientUtil.createCookie(urlCookieName, getReqURL(req), cookieLifeTime, req);
                if (clientConfig.isHttpsRequired() == true && isHttpsRequest) {
                    cookie.setSecure(true);
                }
                res.addCookie(c);
            }

        } catch (UnsupportedEncodingException e) {
            Tr.error(tc, "OIDC_CLIENT_AUTHORIZE_ERR", new Object[] { clientConfig.getClientId(), e.getLocalizedMessage(), ClientConstants.CHARSET });
            return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
        } catch (IOException ioe) {
            Tr.error(tc, "OIDC_CLIENT_AUTHORIZE_ERR", new Object[] { clientConfig.getClientId(), ioe.getLocalizedMessage(), ClientConstants.CHARSET });
            return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);

        }

        return new ProviderAuthenticationResult(AuthResult.REDIRECT_TO_PROVIDER, HttpServletResponse.SC_OK, null, null, null, authzEndPointUrlWithQuery);
    }