Search in sources :

Example 51 with CredentialsProvider

use of org.apache.http.client.CredentialsProvider 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 52 with CredentialsProvider

use of org.apache.http.client.CredentialsProvider 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 53 with CredentialsProvider

use of org.apache.http.client.CredentialsProvider 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 54 with CredentialsProvider

use of org.apache.http.client.CredentialsProvider 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)

Example 55 with CredentialsProvider

use of org.apache.http.client.CredentialsProvider in project XobotOS by xamarin.

the class DefaultRequestDirector method createTunnelToTarget.

// establishConnection
/**
     * Creates a tunnel to the target server.
     * The connection must be established to the (last) proxy.
     * A CONNECT request for tunnelling through the proxy will
     * be created and sent, the response received and checked.
     * This method does <i>not</i> update the connection with
     * information about the tunnel, that is left to the caller.
     *
     * @param route     the route to establish
     * @param context   the context for request execution
     *
     * @return  <code>true</code> if the tunnelled route is secure,
     *          <code>false</code> otherwise.
     *          The implementation here always returns <code>false</code>,
     *          but derived classes may override.
     *
     * @throws HttpException    in case of a problem
     * @throws IOException      in case of an IO problem
     */
protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException {
    HttpHost proxy = route.getProxyHost();
    HttpHost target = route.getTargetHost();
    HttpResponse response = null;
    boolean done = false;
    while (!done) {
        done = true;
        if (!this.managedConn.isOpen()) {
            this.managedConn.open(route, context, this.params);
        }
        HttpRequest connect = createConnectRequest(route, context);
        String agent = HttpProtocolParams.getUserAgent(params);
        if (agent != null) {
            connect.addHeader(HTTP.USER_AGENT, agent);
        }
        connect.addHeader(HTTP.TARGET_HOST, target.toHostString());
        AuthScheme authScheme = this.proxyAuthState.getAuthScheme();
        AuthScope authScope = this.proxyAuthState.getAuthScope();
        Credentials creds = this.proxyAuthState.getCredentials();
        if (creds != null) {
            if (authScope != null || !authScheme.isConnectionBased()) {
                try {
                    connect.addHeader(authScheme.authenticate(creds, connect));
                } catch (AuthenticationException ex) {
                    if (this.log.isErrorEnabled()) {
                        this.log.error("Proxy authentication error: " + ex.getMessage());
                    }
                }
            }
        }
        response = requestExec.execute(connect, this.managedConn, context);
        int status = response.getStatusLine().getStatusCode();
        if (status < 200) {
            throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
        }
        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
            if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
                this.log.debug("Proxy requested authentication");
                Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
                try {
                    processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
                } catch (AuthenticationException ex) {
                    if (this.log.isWarnEnabled()) {
                        this.log.warn("Authentication error: " + ex.getMessage());
                        break;
                    }
                }
                updateAuthState(this.proxyAuthState, proxy, credsProvider);
                if (this.proxyAuthState.getCredentials() != null) {
                    done = false;
                    // Retry request
                    if (this.reuseStrategy.keepAlive(response, context)) {
                        this.log.debug("Connection kept alive");
                        // Consume response content
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            entity.consumeContent();
                        }
                    } else {
                        this.managedConn.close();
                    }
                }
            } else {
                // Reset proxy auth scope
                this.proxyAuthState.setAuthScope(null);
            }
        }
    }
    int status = response.getStatusLine().getStatusCode();
    if (status > 299) {
        // Buffer response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new BufferedHttpEntity(entity));
        }
        this.managedConn.close();
        throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
    }
    this.managedConn.markReusable();
    // Leave it to derived classes, consider insecure by default here.
    return false;
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) AbortableHttpRequest(org.apache.http.client.methods.AbortableHttpRequest) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) AuthenticationException(org.apache.http.auth.AuthenticationException) HttpResponse(org.apache.http.HttpResponse) CredentialsProvider(org.apache.http.client.CredentialsProvider) AuthScheme(org.apache.http.auth.AuthScheme) Header(org.apache.http.Header) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) HttpException(org.apache.http.HttpException) Credentials(org.apache.http.auth.Credentials)

Aggregations

CredentialsProvider (org.apache.http.client.CredentialsProvider)92 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)65 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)57 AuthScope (org.apache.http.auth.AuthScope)51 HttpHost (org.apache.http.HttpHost)28 HttpGet (org.apache.http.client.methods.HttpGet)19 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)17 Test (org.junit.Test)17 HttpResponse (org.apache.http.HttpResponse)16 Credentials (org.apache.http.auth.Credentials)16 IOException (java.io.IOException)13 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)12 BasicScheme (org.apache.http.impl.auth.BasicScheme)12 Header (org.apache.http.Header)11 HttpRequest (org.apache.http.HttpRequest)10 AuthCache (org.apache.http.client.AuthCache)10 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)10 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)10 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)9 HttpEntity (org.apache.http.HttpEntity)8