Search in sources :

Example 96 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project weixin-java-tools by chanjarster.

the class WxMpServiceImpl method setWxMpConfigStorage.

public void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider) {
    this.wxMpConfigStorage = wxConfigProvider;
    String http_proxy_host = wxMpConfigStorage.getHttp_proxy_host();
    int http_proxy_port = wxMpConfigStorage.getHttp_proxy_port();
    String http_proxy_username = wxMpConfigStorage.getHttp_proxy_username();
    String http_proxy_password = wxMpConfigStorage.getHttp_proxy_password();
    final HttpClientBuilder builder = HttpClients.custom();
    if (StringUtils.isNotBlank(http_proxy_host)) {
        // 使用代理服务器
        if (StringUtils.isNotBlank(http_proxy_username)) {
            // 需要用户认证的代理服务器
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(http_proxy_host, http_proxy_port), new UsernamePasswordCredentials(http_proxy_username, http_proxy_password));
            builder.setDefaultCredentialsProvider(credsProvider);
        } else {
        // 无需用户认证的代理服务器
        }
        httpProxy = new HttpHost(http_proxy_host, http_proxy_port);
    }
    if (wxConfigProvider.getSSLContext() != null) {
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(wxConfigProvider.getSSLContext(), new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        builder.setSSLSocketFactory(sslsf);
    }
    httpClient = builder.build();
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 97 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project DataX by alibaba.

the class HttpClientUtil method setBasicAuth.

public static void setBasicAuth(String username, String password) {
    provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 98 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project syncany by syncany.

the class CommandLineClient method sendToRest.

private int sendToRest(Command command, String commandName, String[] commandArgs, File portFile) {
    try {
        // Read port config (for daemon) from port file
        PortTO portConfig = readPortConfig(portFile);
        // Create authentication details
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(SERVER_HOSTNAME, portConfig.getPort()), new UsernamePasswordCredentials(portConfig.getUser().getUsername(), portConfig.getUser().getPassword()));
        // Allow all hostnames in CN; this is okay as long as hostname is localhost/127.0.0.1!
        // See: https://github.com/syncany/syncany/pull/196#issuecomment-52197017
        X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();
        // Fetch the SSL context (using the user key/trust store)
        SSLContext sslContext = UserConfig.createUserSSLContext();
        // Create client with authentication details
        CloseableHttpClient client = HttpClients.custom().setSslcontext(sslContext).setHostnameVerifier(hostnameVerifier).setDefaultCredentialsProvider(credentialsProvider).build();
        // Build and send request, print response
        Request request = buildFolderRequestFromCommand(command, commandName, commandArgs, config.getLocalDir().getAbsolutePath());
        String serverUri = SERVER_SCHEMA + SERVER_HOSTNAME + ":" + portConfig.getPort() + SERVER_REST_API;
        String xmlMessageString = XmlMessageFactory.toXml(request);
        StringEntity xmlMessageEntity = new StringEntity(xmlMessageString);
        HttpPost httpPost = new HttpPost(serverUri);
        httpPost.setEntity(xmlMessageEntity);
        logger.log(Level.INFO, "Sending HTTP Request to: " + serverUri);
        logger.log(Level.FINE, httpPost.toString());
        logger.log(Level.FINE, xmlMessageString);
        HttpResponse httpResponse = client.execute(httpPost);
        int exitCode = handleRestResponse(command, httpResponse);
        return exitCode;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Command " + command.toString() + " FAILED. ", e);
        return showErrorAndExit(e.getMessage());
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) Request(org.syncany.operations.daemon.messages.api.Request) FolderRequest(org.syncany.operations.daemon.messages.api.FolderRequest) PortTO(org.syncany.config.to.PortTO) HttpResponse(org.apache.http.HttpResponse) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) SSLContext(javax.net.ssl.SSLContext) ConfigException(org.syncany.config.ConfigException) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) StringEntity(org.apache.http.entity.StringEntity) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) AuthScope(org.apache.http.auth.AuthScope)

Example 99 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project openhab1-addons by openhab.

the class Tr064Comm method createTr064HttpClient.

/***
     * Creates a apache HTTP Client object, ignoring SSL Exceptions like self signed certificates
     * and sets Auth. Scheme to Digest Auth
     *
     * @param fboxUrl the URL from config file of fbox to connect to
     * @return the ready-to-use httpclient for tr064 requests
     */
private CloseableHttpClient createTr064HttpClient(String fboxUrl) {
    CloseableHttpClient hc = null;
    // Convert URL String from config in easy explotable URI object
    URIBuilder uriFbox = null;
    try {
        uriFbox = new URIBuilder(fboxUrl);
    } catch (URISyntaxException e) {
        logger.error("Invalid FritzBox URL! {}", e.getMessage());
        return null;
    }
    // Create context of the http client
    _httpClientContext = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();
    _httpClientContext.setCookieStore(cookieStore);
    // SETUP AUTH
    // Auth is specific for this target
    HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme());
    // Add digest authentication with username/pw from global config
    CredentialsProvider credp = new BasicCredentialsProvider();
    credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(_user, _pw));
    // Create AuthCache instance. Manages authentication based on server response
    AuthCache authCache = new BasicAuthCache();
    // Generate DIGEST scheme object, initialize it and add it to the local auth cache. Digeste is standard for fbox
    // auth SOAP
    DigestScheme digestAuth = new DigestScheme();
    // known from fbox specification
    digestAuth.overrideParamter("realm", "HTTPS Access");
    // never known at first request
    digestAuth.overrideParamter("nonce", "");
    authCache.put(target, digestAuth);
    // Add AuthCache to the execution context
    _httpClientContext.setAuthCache(authCache);
    // SETUP SSL TRUST
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    SSLConnectionSocketFactory sslsf = null;
    try {
        // accept self signed certs
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        // dont
        sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null, new NoopHostnameVerifier());
    // verify
    // hostname
    // against
    // cert
    // CN
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }
    // Set timeout values
    RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000).setConnectionRequestTimeout(4000).build();
    // BUILDER
    // setup builder with parameters defined before
    hc = // set the SSL options which trust every self signed
    HttpClientBuilder.create().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(// set auth options using digest
    credp).setDefaultRequestConfig(// set the request config specifying timeout
    rc).build();
    return hc;
}
Also used : DigestScheme(org.apache.http.impl.auth.DigestScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) URISyntaxException(java.net.URISyntaxException) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) XPathExpressionException(javax.xml.xpath.XPathExpressionException) URISyntaxException(java.net.URISyntaxException) SOAPException(javax.xml.soap.SOAPException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) URIBuilder(org.apache.http.client.utils.URIBuilder) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy)

Example 100 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project openhab1-addons by openhab.

the class HttpComponentsHelper method setup.

/**
     * prepare for the https connection
     * call this in the constructor of the class that does the connection if
     * it's used multiple times
     */
private void setup() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    // http scheme
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // https scheme
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
    params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));
    params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf8");
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    // set the user credentials for our site "example.com"
    credentialsProvider.setCredentials(new AuthScope("example.com", AuthScope.ANY_PORT), new UsernamePasswordCredentials("UserNameHere", "UserPasswordHere"));
    clientConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
    context = new BasicHttpContext();
    context.setAttribute("http.auth.credentials-provider", credentialsProvider);
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) Scheme(org.apache.http.conn.scheme.Scheme) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) AuthScope(org.apache.http.auth.AuthScope) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicHttpParams(org.apache.http.params.BasicHttpParams) ConnPerRouteBean(org.apache.http.conn.params.ConnPerRouteBean) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Aggregations

BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)192 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)162 CredentialsProvider (org.apache.http.client.CredentialsProvider)147 AuthScope (org.apache.http.auth.AuthScope)104 HttpHost (org.apache.http.HttpHost)76 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)53 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)41 HttpResponse (org.apache.http.HttpResponse)38 IOException (java.io.IOException)35 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)31 HttpGet (org.apache.http.client.methods.HttpGet)30 HttpClient (org.apache.http.client.HttpClient)29 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)29 AuthCache (org.apache.http.client.AuthCache)28 BasicScheme (org.apache.http.impl.auth.BasicScheme)27 RequestConfig (org.apache.http.client.config.RequestConfig)25 HttpPost (org.apache.http.client.methods.HttpPost)20 Credentials (org.apache.http.auth.Credentials)19 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)19 Test (org.junit.Test)16