Search in sources :

Example 71 with UsernamePasswordCredentials

use of org.apache.http.auth.UsernamePasswordCredentials in project ecf by eclipse.

the class HttpClientFileSystemBrowser method getFileRequestCredentials.

/**
 * Retrieves the credentials for requesting the file.
 * @return the {@link Credentials} necessary to retrieve the file
 * @throws UnsupportedCallbackException if the callback fails
 * @throws IOException if IO fails
 * @since 5.0
 */
protected Credentials getFileRequestCredentials() throws UnsupportedCallbackException, IOException {
    if (connectContext == null)
        return null;
    final CallbackHandler callbackHandler = connectContext.getCallbackHandler();
    if (callbackHandler == null)
        return null;
    final NameCallback usernameCallback = new NameCallback(USERNAME_PREFIX);
    final ObjectCallback passwordCallback = new ObjectCallback();
    callbackHandler.handle(new Callback[] { usernameCallback, passwordCallback });
    username = usernameCallback.getName();
    password = (String) passwordCallback.getObject();
    return new UsernamePasswordCredentials(username, password);
}
Also used : CallbackHandler(org.eclipse.ecf.core.security.CallbackHandler) NameCallback(org.eclipse.ecf.core.security.NameCallback) ObjectCallback(org.eclipse.ecf.core.security.ObjectCallback) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 72 with UsernamePasswordCredentials

use of org.apache.http.auth.UsernamePasswordCredentials in project ecf by eclipse.

the class HttpClientRetrieveFileTransfer method getFileRequestCredentials.

/**
 * @return Credentials file request credentials
 * @throws UnsupportedCallbackException if some problem
 * @throws IOException if some problem
 * @since 5.0
 */
protected Credentials getFileRequestCredentials() throws UnsupportedCallbackException, IOException {
    if (connectContext == null)
        return null;
    final CallbackHandler callbackHandler = connectContext.getCallbackHandler();
    if (callbackHandler == null)
        return null;
    final NameCallback usernameCallback = new NameCallback(USERNAME_PREFIX);
    final ObjectCallback passwordCallback = new ObjectCallback();
    callbackHandler.handle(new Callback[] { usernameCallback, passwordCallback });
    username = usernameCallback.getName();
    password = (String) passwordCallback.getObject();
    return new UsernamePasswordCredentials(username, password);
}
Also used : CallbackHandler(org.eclipse.ecf.core.security.CallbackHandler) NameCallback(org.eclipse.ecf.core.security.NameCallback) ObjectCallback(org.eclipse.ecf.core.security.ObjectCallback) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 73 with UsernamePasswordCredentials

use of org.apache.http.auth.UsernamePasswordCredentials in project ma-core-public by infiniteautomation.

the class Common method getHttpClient.

public static HttpClient getHttpClient(int timeout) {
    // Create global request configuration
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setSocketTimeout(timeout).setConnectTimeout(timeout).build();
    if (SystemSettingsDao.getBooleanValue(SystemSettingsDao.HTTP_CLIENT_USE_PROXY)) {
        String proxyHost = SystemSettingsDao.getValue(SystemSettingsDao.HTTP_CLIENT_PROXY_SERVER);
        int proxyPort = SystemSettingsDao.getIntValue(SystemSettingsDao.HTTP_CLIENT_PROXY_PORT);
        String username = SystemSettingsDao.getValue(SystemSettingsDao.HTTP_CLIENT_PROXY_USERNAME, "");
        String password = SystemSettingsDao.getValue(SystemSettingsDao.HTTP_CLIENT_PROXY_PASSWORD, "");
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(username, password));
        // Create an HttpClient with the given custom dependencies and configuration.
        CloseableHttpClient httpclient = HttpClients.custom().setProxy(new HttpHost(proxyHost, proxyPort)).setDefaultRequestConfig(defaultRequestConfig).setDefaultCredentialsProvider(credentialsProvider).build();
        return httpclient;
    } else {
        // Create an HttpClient with the given custom dependencies and configuration.
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
        return httpclient;
    }
// LEGACY CODE LEFT HERE UNTIL Testing of above code is confirmed as working
// DefaultHttpClient client = new DefaultHttpClient();
// client.getParams().setParameter("http.socket.timeout", timeout);
// client.getParams().setParameter("http.connection.timeout", timeout);
// client.getParams().setParameter("http.connection-manager.timeout", timeout);
// client.getParams().setParameter("http.protocol.head-body-timeout", timeout);
// 
// if (SystemSettingsDao.getBooleanValue(SystemSettingsDao.HTTP_CLIENT_USE_PROXY)) {
// String proxyHost = SystemSettingsDao.getValue(SystemSettingsDao.HTTP_CLIENT_PROXY_SERVER);
// int proxyPort = SystemSettingsDao.getIntValue(SystemSettingsDao.HTTP_CLIENT_PROXY_PORT);
// String username = SystemSettingsDao.getValue(SystemSettingsDao.HTTP_CLIENT_PROXY_USERNAME, "");
// String password = SystemSettingsDao.getValue(SystemSettingsDao.HTTP_CLIENT_PROXY_PASSWORD, "");
// 
// client.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
// new UsernamePasswordCredentials(username, password));
// 
// }
// 
// return client;
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 74 with UsernamePasswordCredentials

use of org.apache.http.auth.UsernamePasswordCredentials in project fabric-sdk-java by hyperledger.

the class HFCAClient method enroll.

/**
 * Enroll the user with member service
 *
 * @param user   Identity name to enroll
 * @param secret Secret returned via registration
 * @param req    Enrollment request with the following fields: hosts, profile, csr, label, keypair
 * @return enrollment
 * @throws EnrollmentException
 * @throws InvalidArgumentException
 */
public Enrollment enroll(String user, String secret, EnrollmentRequest req) throws EnrollmentException, InvalidArgumentException {
    logger.debug(format("url:%s enroll user: %s", url, user));
    if (Utils.isNullOrEmpty(user)) {
        throw new InvalidArgumentException("enrollment user is not set");
    }
    if (Utils.isNullOrEmpty(secret)) {
        throw new InvalidArgumentException("enrollment secret is not set");
    }
    if (cryptoSuite == null) {
        throw new InvalidArgumentException("Crypto primitives not set.");
    }
    setUpSSL();
    try {
        String pem = req.getCsr();
        KeyPair keypair = req.getKeyPair();
        if (null != pem && keypair == null) {
            throw new InvalidArgumentException("If certificate signing request is supplied the key pair needs to be supplied too.");
        }
        if (keypair == null) {
            logger.debug("[HFCAClient.enroll] Generating keys...");
            // generate ECDSA keys: signing and encryption keys
            keypair = cryptoSuite.keyGen();
            logger.debug("[HFCAClient.enroll] Generating keys...done!");
        }
        if (pem == null) {
            String csr = cryptoSuite.generateCertificationRequest(user, keypair);
            req.setCSR(csr);
        }
        if (caName != null && !caName.isEmpty()) {
            req.setCAName(caName);
        }
        String body = req.toJson();
        String responseBody = httpPost(url + HFCA_ENROLL, body, new UsernamePasswordCredentials(user, secret));
        logger.debug("response:" + responseBody);
        JsonReader reader = Json.createReader(new StringReader(responseBody));
        JsonObject jsonst = (JsonObject) reader.read();
        boolean success = jsonst.getBoolean("success");
        logger.debug(format("[HFCAClient] enroll success:[%s]", success));
        if (!success) {
            throw new EnrollmentException(format("FabricCA failed enrollment for user %s response success is false.", user));
        }
        JsonObject result = jsonst.getJsonObject("result");
        if (result == null) {
            throw new EnrollmentException(format("FabricCA failed enrollment for user %s - response did not contain a result", user));
        }
        Base64.Decoder b64dec = Base64.getDecoder();
        String signedPem = new String(b64dec.decode(result.getString("Cert").getBytes(UTF_8)));
        logger.debug(format("[HFCAClient] enroll returned pem:[%s]", signedPem));
        JsonArray messages = jsonst.getJsonArray("messages");
        if (messages != null && !messages.isEmpty()) {
            JsonObject jo = messages.getJsonObject(0);
            String message = format("Enroll request response message [code %d]: %s", jo.getInt("code"), jo.getString("message"));
            logger.info(message);
        }
        logger.debug("Enrollment done.");
        return new HFCAEnrollment(keypair, signedPem);
    } catch (EnrollmentException ee) {
        logger.error(format("url:%s, user:%s  error:%s", url, user, ee.getMessage()), ee);
        throw ee;
    } catch (Exception e) {
        EnrollmentException ee = new EnrollmentException(format("Url:%s, Failed to enroll user %s ", url, user), e);
        logger.error(e.getMessage(), e);
        throw ee;
    }
}
Also used : KeyPair(java.security.KeyPair) Base64(java.util.Base64) EnrollmentException(org.hyperledger.fabric_ca.sdk.exception.EnrollmentException) JsonObject(javax.json.JsonObject) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) InvalidArgumentException(org.hyperledger.fabric_ca.sdk.exception.InvalidArgumentException) URISyntaxException(java.net.URISyntaxException) RegistrationException(org.hyperledger.fabric_ca.sdk.exception.RegistrationException) KeyStoreException(java.security.KeyStoreException) AffiliationException(org.hyperledger.fabric_ca.sdk.exception.AffiliationException) GenerateCRLException(org.hyperledger.fabric_ca.sdk.exception.GenerateCRLException) KeyManagementException(java.security.KeyManagementException) IdentityException(org.hyperledger.fabric_ca.sdk.exception.IdentityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) EnrollmentException(org.hyperledger.fabric_ca.sdk.exception.EnrollmentException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) RevocationException(org.hyperledger.fabric_ca.sdk.exception.RevocationException) ParseException(org.apache.http.ParseException) MalformedURLException(java.net.MalformedURLException) InfoException(org.hyperledger.fabric_ca.sdk.exception.InfoException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) HTTPException(org.hyperledger.fabric_ca.sdk.exception.HTTPException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) JsonArray(javax.json.JsonArray) InvalidArgumentException(org.hyperledger.fabric_ca.sdk.exception.InvalidArgumentException) StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader)

Example 75 with UsernamePasswordCredentials

use of org.apache.http.auth.UsernamePasswordCredentials in project directory-fortress-core by apache.

the class RestUtils method getCredentialProvider.

private CredentialsProvider getCredentialProvider(String uid, String password) {
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(httpHost, Integer.valueOf(httpPort)), new UsernamePasswordCredentials(uid == null ? httpUid : uid, password == null ? httpPw : password));
    return credentialsProvider;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AuthScope(org.apache.http.auth.AuthScope) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Aggregations

UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)337 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)212 CredentialsProvider (org.apache.http.client.CredentialsProvider)189 AuthScope (org.apache.http.auth.AuthScope)163 HttpHost (org.apache.http.HttpHost)95 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)78 HttpGet (org.apache.http.client.methods.HttpGet)73 IOException (java.io.IOException)54 BasicScheme (org.apache.http.impl.auth.BasicScheme)53 Test (org.junit.Test)53 HttpResponse (org.apache.http.HttpResponse)52 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)46 Credentials (org.apache.http.auth.Credentials)44 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)43 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)37 URI (java.net.URI)34 AuthCache (org.apache.http.client.AuthCache)32 HttpClient (org.apache.http.client.HttpClient)31 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)31 HttpPost (org.apache.http.client.methods.HttpPost)29