Query Snowflake to obtain IDP token url and IDP SSO url

@param loginInput
@throws SnowflakeSQLException
488082
private static JsonNode federatedFlowStep1(LoginInput loginInput)
  throws SnowflakeSQLException
  {
    JsonNode dataNode = null;
    try
    {
      URIBuilder fedUriBuilder = new URIBuilder(loginInput.getServerUrl());
      fedUriBuilder.setPath(SF_PATH_AUTHENTICATOR_REQUEST);
      URI fedUrlUri = fedUriBuilder.build();

      Map<String, Object> data = new HashMap<>();
      data.put(ClientAuthnParameter.ACCOUNT_NAME.name(),
               loginInput.getAccountName());
      data.put(ClientAuthnParameter.AUTHENTICATOR.name(),
               loginInput.getAuthenticator());
      data.put(ClientAuthnParameter.CLIENT_APP_ID.name(), loginInput.getAppId());
      data.put(ClientAuthnParameter.CLIENT_APP_VERSION.name(),
               loginInput.getAppVersion());

      ClientAuthnDTO authnData = new ClientAuthnDTO();
      authnData.setData(data);
      String json = mapper.writeValueAsString(authnData);

      // attach the login info json body to the post request
      StringEntity input = new StringEntity(json, Charset.forName("UTF-8"));
      input.setContentType("application/json");
      HttpPost postRequest = new HttpPost(fedUrlUri);
      postRequest.setEntity(input);
      postRequest.addHeader("accept", "application/json");

      final String gsResponse = HttpUtil.executeRequest(postRequest,
                                                        loginInput.getLoginTimeout(), 0, null);
      logger.debug("authenticator-request response: {}", gsResponse);
      JsonNode jsonNode = mapper.readTree(gsResponse);

      // check the success field first
      if (!jsonNode.path("success").asBoolean())
      {
        logger.debug("response = {}", gsResponse);
        String errorCode = jsonNode.path("code").asText();
        throw new SnowflakeSQLException(
            SqlState.SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION,
            ErrorCode.CONNECTION_ERROR.getMessageCode(),
            errorCode, jsonNode.path("message").asText());
      }

      // session token is in the data field of the returned json response
      dataNode = jsonNode.path("data");
    }
    catch (IOException | URISyntaxException ex)
    {
      handleFederatedFlowError(loginInput, ex);
    }
    return dataNode;
  }
651056
public function getLoginUrl($loginTicket, $target, $agentId = null)
    {
        $params = [
            'login_ticket' => $loginTicket,
            'target'       => $target,
            'agentid'      => $agentId,
        ];

        return $this->parseJSON('json', [self::API_GET_LOGIN_URL, $params]);
    }
721540
private String getSSOUrl(int port) throws SFException, SnowflakeSQLException
  {
    try
    {
      String serverUrl = loginInput.getServerUrl();
      String authenticator = loginInput.getAuthenticator();

      URIBuilder fedUriBuilder = new URIBuilder(serverUrl);
      fedUriBuilder.setPath(SessionUtil.SF_PATH_AUTHENTICATOR_REQUEST);
      URI fedUrlUri = fedUriBuilder.build();

      HttpPost postRequest = this.handlers.build(fedUrlUri);

      ClientAuthnDTO authnData = new ClientAuthnDTO();
      Map<String, Object> data = new HashMap<>();

      data.put(ClientAuthnParameter.AUTHENTICATOR.name(), authenticator);
      data.put(ClientAuthnParameter.ACCOUNT_NAME.name(),
               loginInput.getAccountName());
      data.put(ClientAuthnParameter.LOGIN_NAME.name(),
               loginInput.getUserName());
      data.put(ClientAuthnParameter.BROWSER_MODE_REDIRECT_PORT.name(),
               Integer.toString(port));
      data.put(ClientAuthnParameter.CLIENT_APP_ID.name(), loginInput.getAppId());
      data.put(ClientAuthnParameter.CLIENT_APP_VERSION.name(),
               loginInput.getAppVersion());

      authnData.setData(data);
      String json = mapper.writeValueAsString(authnData);

      // attach the login info json body to the post request
      StringEntity input = new StringEntity(json, Charset.forName("UTF-8"));
      input.setContentType("application/json");
      postRequest.setEntity(input);

      postRequest.addHeader("accept", "application/json");

      String theString = HttpUtil.executeRequest(postRequest,
                                                 loginInput.getLoginTimeout(), 0, null);

      logger.debug("authenticator-request response: {}", theString);

      // general method, same as with data binding
      JsonNode jsonNode = mapper.readTree(theString);

      // check the success field first
      if (!jsonNode.path("success").asBoolean())
      {
        logger.debug("response = {}", theString);
        String errorCode = jsonNode.path("code").asText();
        throw new SnowflakeSQLException(
            SqlState.SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION,
            new Integer(errorCode),
            jsonNode.path("message").asText());
      }

      JsonNode dataNode = jsonNode.path("data");

      // session token is in the data field of the returned json response
      this.proofKey = dataNode.path("proofKey").asText();
      return dataNode.path("ssoUrl").asText();
    }
    catch (IOException | URISyntaxException ex)
    {
      throw new SFException(ex, ErrorCode.NETWORK_ERROR, ex.getMessage());
    }
  }
1209576
public User get(Connection conn,String loginname, String cryptpassword) throws SQLException {
        ResultSetHandler<User> h = new BeanHandler<User>(User.class);
        String sql =
            "SELECT id,username,fullname,type,emailaddress,registered_ts,invited_by,enabled \n"+
            "FROM userbase \n";
        if (loginname.indexOf("@") < 0)
            sql = sql + "WHERE username=? AND password=? and enabled=true";
        else
            sql = sql + "WHERE emailaddress=? AND password=? and enabled=true";
        return run.query(conn, sql, h, loginname, cryptpassword);
    }
263840
@Override
  public void startSSPI() throws SQLException, IOException {

    /*
     * We usually use SSPI negotiation (spnego), but it's disabled if the client asked for GSSPI and
     * usespngo isn't explicitly turned on.
     */
    final String securityPackage = enableNegotiate ? "negotiate" : "kerberos";

    LOGGER.log(Level.FINEST, "Beginning SSPI/Kerberos negotiation with SSPI package: {0}", securityPackage);

    try {
      /*
       * Acquire a handle for the local Windows login credentials for the current user
       *
       * See AcquireCredentialsHandle
       * (http://msdn.microsoft.com/en-us/library/windows/desktop/aa374712%28v=vs.85%29.aspx)
       *
       * This corresponds to pg_SSPI_startup in libpq/fe-auth.c .
       */
      try {
        clientCredentials = WindowsCredentialsHandleImpl.getCurrent(securityPackage);
        clientCredentials.initialize();
      } catch (Win32Exception ex) {
        throw new PSQLException("Could not obtain local Windows credentials for SSPI",
            PSQLState.CONNECTION_UNABLE_TO_CONNECT /* TODO: Should be authentication error */, ex);
      }

      try {
        targetName = makeSPN();

        LOGGER.log(Level.FINEST, "SSPI target name: {0}", targetName);

        sspiContext = new WindowsSecurityContextImpl();
        sspiContext.setPrincipalName(targetName);
        sspiContext.setCredentialsHandle(clientCredentials);
        sspiContext.setSecurityPackage(securityPackage);
        sspiContext.initialize(null, null, targetName);
      } catch (Win32Exception ex) {
        throw new PSQLException("Could not initialize SSPI security context",
            PSQLState.CONNECTION_UNABLE_TO_CONNECT /* TODO: Should be auth error */, ex);
      }

      sendSSPIResponse(sspiContext.getToken());
      LOGGER.log(Level.FINEST, "Sent first SSPI negotiation message");
    } catch (NoClassDefFoundError ex) {
      throw new PSQLException(
          "SSPI cannot be used, Waffle or its dependencies are missing from the classpath",
          PSQLState.NOT_IMPLEMENTED, ex);
    }
  }
1200650
@Override
    @Deprecated
    protected void initializeInternal() throws RepositoryException {
        this.databaseClient = DatabaseClientFactory.newClient(host,port,user,password,DatabaseClientFactory.Authentication.valueOf(auth));
        this.client = new MarkLogicClient(databaseClient);
    }
537654
protected AuthenticationBuilder authenticateInternal(final AuthenticationTransaction transaction) throws AuthenticationException {
        val credentials = transaction.getCredentials();
        LOGGER.debug("Authentication credentials provided for this transaction are [{}]", credentials);

        if (credentials.isEmpty()) {
            LOGGER.error("Resolved authentication handlers for this transaction are empty");
            throw new AuthenticationException("Resolved credentials for this transaction are empty");
        }

        val builder = new DefaultAuthenticationBuilder(NullPrincipal.getInstance());
        credentials.forEach(cred -> builder.addCredential(new BasicCredentialMetaData(cred)));
        
        val handlerSet = this.authenticationEventExecutionPlan.getAuthenticationHandlersForTransaction(transaction);
        LOGGER.debug("Candidate resolved authentication handlers for this transaction are [{}]", handlerSet);

        if (handlerSet.isEmpty()) {
            LOGGER.error("Resolved authentication handlers for this transaction are empty");
            throw new AuthenticationException(builder.getFailures(), builder.getSuccesses());
        }

        try {
            val it = credentials.iterator();
            AuthenticationCredentialsThreadLocalBinder.clearInProgressAuthentication();
            while (it.hasNext()) {
                val credential = it.next();
                LOGGER.debug("Attempting to authenticate credential [{}]", credential);

                val itHandlers = handlerSet.iterator();
                var proceedWithNextHandler = true;
                while (proceedWithNextHandler && itHandlers.hasNext()) {
                    val handler = itHandlers.next();
                    if (handler.supports(credential)) {
                        try {
                            val resolver = getPrincipalResolverLinkedToHandlerIfAny(handler, transaction);
                            LOGGER.debug("Attempting authentication of [{}] using [{}]", credential.getId(), handler.getName());
                            authenticateAndResolvePrincipal(builder, credential, resolver, handler);

                            val authnResult = builder.build();
                            AuthenticationCredentialsThreadLocalBinder.bindInProgress(authnResult);
                            val failures = evaluateAuthenticationPolicies(authnResult, transaction, handlerSet);
                            proceedWithNextHandler = !failures.getKey();
                        } catch (final Exception e) {
                            LOGGER.error("Authentication has failed. Credentials may be incorrect or CAS cannot "
                                + "find authentication handler that supports [{}] of type [{}]. Examine the configuration to "
                                + "ensure a method of authentication is defined and analyze CAS logs at DEBUG level to trace "
                                + "the authentication event.", credential, credential.getClass().getSimpleName());

                            handleAuthenticationException(e, handler.getName(), builder);
                            proceedWithNextHandler = true;
                        }
                    } else {
                        LOGGER.debug("Authentication handler [{}] does not support the credential type [{}]. Trying next...", handler.getName(), credential);
                    }
                }
            }
            evaluateFinalAuthentication(builder, transaction, handlerSet);
            return builder;
        } finally {
            AuthenticationCredentialsThreadLocalBinder.clearInProgressAuthentication();
        }
    }
466141
public function onFailedLogin(Event $event, $clientIp, $loginField, $loginFieldValue)
    {
        $recognitionTime = Wasabi::setting('Core.Auth.failed_login_recognition_time');
        $maxLoginAttempts = Wasabi::setting('Core.Auth.max_login_attempts');
        $past = (new \DateTime())->modify('-' . $recognitionTime . ' minutes');

        $LoginLogs = TableRegistry::get('Wasabi/Core.LoginLogs');

        $loginLog = $LoginLogs->newEntity([
            'client_ip' => $clientIp,
            'login_field' => $loginField,
            'login_field_value' => $loginFieldValue,
            'success' => false
        ]);

        $failedLogins = $LoginLogs->find()
            ->where([
                'client_ip' => $clientIp,
                'success' => false
            ])
            ->andWhere(function (QueryExpression $exp) use ($past) {
                return $exp->gt('created', $past->format('Y-m-d H:i:s'));
            })
            ->count();

        if (($failedLogins + 1) >= $maxLoginAttempts) {
            $loginLog->set('blocked', true);
        }

        $LoginLogs->save($loginLog);
    }
1244032
void init() throws SocialLoginException {
        if (sslSupport != null) {
            Properties sslProps = null;
            this.jsseHelper = sslSupport.getJSSEHelper();
            if (this.jsseHelper != null) {
                try {
                    if (sslRef != null) {
                        sslProps = this.jsseHelper.getProperties(sslRef); // SSLConfig
                    } else {
                        Map<String, Object> connectionInfo = new HashMap<String, Object>();
                        connectionInfo.put(Constants.CONNECTION_INFO_DIRECTION, Constants.DIRECTION_INBOUND);
                        sslProps = this.jsseHelper.getProperties(null, connectionInfo, null, true); // default
                        // SSL
                    }
                } catch (SSLException e) {
                    throw new SocialLoginException("ERROR_LOADING_SSL_PROPS", e, new Object[] { e.getLocalizedMessage() });
                }
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "sslConfig (" + sslRef + ") get: " + sslProps);
                }
                if (sslProps != null) {
                    this.sslKeyStoreName = sslProps.getProperty(com.ibm.websphere.ssl.Constants.SSLPROP_KEY_STORE_NAME);
                    this.sslTrustStoreName = sslProps.getProperty(com.ibm.websphere.ssl.Constants.SSLPROP_TRUST_STORE_NAME);
                }
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "sslTrustStoreName: " + this.sslTrustStoreName);
                }
            }
        }
    }
643897
function getIdTokenResult(forceRefresh) {
  if (activeUser() == null) {
    alertError('No user logged in.');
    return;
  }
  activeUser().getIdTokenResult(forceRefresh).then(function(idTokenResult) {
    alertSuccess(JSON.stringify(idTokenResult));
  }, onAuthError);
}
124789
private boolean loginInternal(String nic, String password, int timeInSec) throws IOException {
		// Due to per IP login rate limiting, we synchronize this part of the code.
		// if multiple IP available, it can be sync on public IP based token
		synchronized (ApiOvhCore.class) {
			String oldCK = config.getConsumerKey(nic);
			if (oldCK != null && _consumerKey != null && !oldCK.equals(_consumerKey)) {
				// a new CK is available try it first.
				_consumerKey = oldCK;
				return true;
			}
			OvhCredential token = requestToken(null);
			log.info("Generating a new ConsumerKey as appKey: {} for account {} valid for {} sec, validationUrl:{}",
					this.config.getApplicationKey(), nic, timeInSec, token.validationUrl);

			Document doc = Jsoup.connect(token.validationUrl).get();
			String html = doc.toString();
			if (html.contains("Too much requests"))
				return false;
			// <input type="hidden" name="sT" id="sT" value="XXXXX">
			Element st = doc.getElementById("sT");
			FormElement form = null;
			// get Parent Form
			for (Element elm : st.parents()) {
				// "form".equalsIgnoreCase(elm.tagName())
				if (elm instanceof FormElement) {
					form = (FormElement) elm;
					break;
				}
			}
			Elements inputs = form.select("input");
			Connection validForm = Jsoup.connect(token.validationUrl);
			validForm.followRedirects(false);
			// fill user and password field
			for (Element e : inputs) {
				String name = e.attr("name");
				String value = e.attr("value");
				String type = e.attr("type");
				if ("text".equals(type))
					value = nic;
				else if ("password".equals(type))
					value = password;
				validForm.data(name, value);
			}
			// set Expiration Date
			validForm.data("duration", Integer.toString(timeInSec));
			Document doc2 = validForm.post();
			Elements p = doc2.select("p");
			String pText = p.text();
			if ("The document has moved here.".equals(pText)) {
				log.info("a new consumerKey had been issued for {}", nic);
				this.setCK(nic, token.consumerKey);
				return true;
			}
			if ("Your token is now valid, you can use it in your application".equals(pText)) {
				log.info("a new consumerKey had been issued for {}", nic);
				this.setCK(nic, token.consumerKey);
				return true;
			}
			String error = doc2.select("div.error").text();
			if (error != null && error.length() > 0)
				log.error("Login {} Error:{}", nic, error);
			else {
				String body = doc2.toString();
				if (body.contains("Too much requests. Please retry in 3 seconds. ")) {
					log.error("Too much requests, block all connexion for 3sec, Retry later to connect {}", nic);
					ApiOvhUtils.sleep(3000);
				} else {
					log.error("Unknown Error connecting to {} in body:{}", nic, body);
				}
			}
			return false;
		}
	}
6272
private String getUserFromToken(HiveAuthFactory authFactory, String tokenStr) throws HiveSQLException {
    return authFactory.getUserFromToken(tokenStr);
  }
310928
@Override
  public final API withInjectedLogSite(LogSite logSite) {
    // First call wins (since auto-injection will typically target the log() method at the end of
    // the chain and might not check for previous explicit injection).
    if (this.logSite == null) {
      this.logSite = checkNotNull(logSite, "log site");
    }
    return api();
  }
963834
@Override
    public PrivateKey getPrivateKey() throws SocialLoginException {
        if (this.sslRefInfo == null) {
            SocialLoginService service = socialLoginServiceRef.getService();
            if (service == null) {
                if (tc.isDebugEnabled()) {
                    Tr.debug(tc, "Social login service is not available");
                }
                return null;
            }
            sslRefInfo = createSslRefInfoImpl(service);
        }
        return sslRefInfo.getPrivateKey();
    }
683737
public function getLoginToken(UserInterface $user, UuidInterface $token) : LoginToken
    {
        return new LoginToken(
            $user->getId(),
            $token
        );
    }
962093
public static QueryFilter getIdentityFilter(DecoratedKey key, String cfName, long timestamp)
    {
        return new QueryFilter(key, cfName, new IdentityQueryFilter(), timestamp);
    }
1007855
protected void registerNativeAlpn(SSLEngine engine) {
        if (isNativeAlpnActive()) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "registerNativeAlpn entry " + engine);
            }
            try {
                String[] protocols = new String[] { h2, h1 };
                SSLParameters params = engine.getSSLParameters();
                nativeAlpnPut.invoke(params, (Object) protocols);
                engine.setSSLParameters(params);
                Method m = SSLParameters.class.getMethod("getApplicationProtocols");

            } catch (InvocationTargetException ie) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "registerNativeAlpn exception: " + ie.getTargetException());
                }
            } catch (Exception e) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "registerNativeAlpn exception: " + e);
                }
            }
        }
    }