예제 #1
1
  private HttpClient getClient() {
    if (client == null) {
      HttpClientBuilder clientBuilder = HttpClients.custom();
      RequestConfig.Builder configBuilder = RequestConfig.custom();
      if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        isUsingProxy = true;
        InetSocketAddress adr = (InetSocketAddress) proxy.address();
        clientBuilder.setProxy(new HttpHost(adr.getHostName(), adr.getPort()));
      }
      if (timeout != null) {
        configBuilder.setConnectTimeout(timeout.intValue());
      }
      if (readTimeout != null) {
        configBuilder.setSocketTimeout(readTimeout.intValue());
      }
      if (followRedirects != null) {
        configBuilder.setRedirectsEnabled(followRedirects.booleanValue());
      }
      if (hostnameverifier != null) {
        SSLConnectionSocketFactory sslConnectionFactory =
            new SSLConnectionSocketFactory(getSSLContext(), hostnameverifier);
        clientBuilder.setSSLSocketFactory(sslConnectionFactory);
        Registry<ConnectionSocketFactory> registry =
            RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionFactory)
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .build();
        clientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
      }
      clientBuilder.setDefaultRequestConfig(configBuilder.build());
      client = clientBuilder.build();
    }

    return client;
  }
예제 #2
0
  /**
   * Handle authentication and Proxy'ing
   *
   * @param cb
   * @throws HTTPException
   */
  protected synchronized void setAuthenticationAndProxy(HttpClientBuilder cb) throws HTTPException {
    // First, setup the ssl factory
    cb.setSSLSocketFactory(globalsslfactory);

    // Second, Construct a CredentialsProvider that is
    // the union of the Proxy credentials plus
    // either the global local credentials; local overrides global
    // Unfortunately, we cannot either clone or extract the contents
    // of the client supplied provider, so we are forced (for now)
    // to modify the client supplied provider.

    // Look in the local authcreds for best scope match
    AuthScope bestMatch = HTTPAuthUtil.bestmatch(scope, localcreds.keySet());
    CredentialsProvider cp = null;
    if (bestMatch != null) {
      cp = localcreds.get(bestMatch);
    } else {
      bestMatch = HTTPAuthUtil.bestmatch(scope, globalcreds.keySet());
      if (bestMatch != null) cp = globalcreds.get(bestMatch);
    }
    // Build the proxy credentials and AuthScope
    Credentials proxycreds = null;
    AuthScope proxyscope = null;
    if (proxyuser != null && (httpproxy != null || httpsproxy != null)) {
      if (httpproxy != null) proxyscope = HTTPAuthUtil.hostToAuthScope(httpproxy);
      else // httpsproxy != null
      proxyscope = HTTPAuthUtil.hostToAuthScope(httpsproxy);
      proxycreds = new UsernamePasswordCredentials(proxyuser, proxypwd);
    }
    if (cp == null && proxycreds != null && proxyscope != null) {
      // If client provider is null and proxycreds are not,
      // then use proxycreds alone
      cp = new BasicCredentialsProvider();
      cp.setCredentials(proxyscope, proxycreds);
    } else if (cp != null && proxycreds != null && proxyscope != null) {
      // If client provider is not null and proxycreds are not,
      // then add proxycreds to the client provider
      cp.setCredentials(proxyscope, proxycreds);
    }
    if (cp != null) this.sessioncontext.setCredentialsProvider(cp);
  }
예제 #3
0
  public Session(
      URL url, String login, String password, boolean trustSelfSigned, int maxConnections) {

    _executorService = Executors.newFixedThreadPool(maxConnections);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    credentialsProvider.setCredentials(
        new AuthScope(url.getHost(), url.getPort()),
        new UsernamePasswordCredentials(login, password));

    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

    httpClientBuilder.setMaxConnPerRoute(maxConnections);
    httpClientBuilder.setMaxConnTotal(maxConnections);
    httpClientBuilder.setRoutePlanner(_getHttpRoutePlanner());

    if (trustSelfSigned) {
      try {
        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

        SSLConnectionSocketFactory sslConnectionSocketFactory =
            new SSLConnectionSocketFactory(
                sslContextBuilder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
      } catch (Exception e) {
        _logger.error(e.getMessage(), e);
      }
    }

    _httpClient = httpClientBuilder.build();

    _httpHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
  }
  /**
   * Returns the HttpClient through which the REST call is made. Uses an unsafe TrustStrategy in
   * case the user specified a HTTPS URL and set the ignoreUnverifiedSSLPeer flag.
   *
   * @param logger the logger to log messages to
   * @return the HttpClient
   */
  private HttpClient getHttpClient(PrintStream logger) throws Exception {
    boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer;
    String stashServer = stashServerBaseUrl;
    DescriptorImpl descriptor = getDescriptor();
    if ("".equals(stashServer) || stashServer == null) {
      stashServer = descriptor.getStashRootUrl();
    }
    if (!ignoreUnverifiedSSL) {
      ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl();
    }

    URL url = new URL(stashServer);
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (url.getProtocol().equals("https") && ignoreUnverifiedSSL) {
      // add unsafe trust manager to avoid thrown
      // SSLPeerUnverifiedException
      try {
        TrustStrategy easyStrategy =
            new TrustStrategy() {
              public boolean isTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {
                return true;
              }
            };

        SSLContext sslContext =
            SSLContexts.custom().loadTrustMaterial(null, easyStrategy).useTLS().build();
        SSLConnectionSocketFactory sslConnSocketFactory =
            new SSLConnectionSocketFactory(
                sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        builder.setSSLSocketFactory(sslConnSocketFactory);

        Registry<ConnectionSocketFactory> registry =
            RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnSocketFactory)
                .build();

        HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);

        builder.setConnectionManager(ccm);
      } catch (NoSuchAlgorithmException nsae) {
        logger.println("Couldn't establish SSL context:");
        nsae.printStackTrace(logger);
      } catch (KeyManagementException kme) {
        logger.println("Couldn't initialize SSL context:");
        kme.printStackTrace(logger);
      } catch (KeyStoreException kse) {
        logger.println("Couldn't initialize SSL context:");
        kse.printStackTrace(logger);
      }
    }

    // Configure the proxy, if needed
    // Using the Jenkins methods handles the noProxyHost settings
    ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
    if (proxyConfig != null) {
      Proxy proxy = proxyConfig.createProxy(url.getHost());
      if (proxy != null && proxy.type() == Proxy.Type.HTTP) {
        SocketAddress addr = proxy.address();
        if (addr != null && addr instanceof InetSocketAddress) {
          InetSocketAddress proxyAddr = (InetSocketAddress) addr;
          HttpHost proxyHost =
              new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort());
          builder = builder.setProxy(proxyHost);

          String proxyUser = proxyConfig.getUserName();
          if (proxyUser != null) {
            String proxyPass = proxyConfig.getPassword();
            CredentialsProvider cred = new BasicCredentialsProvider();
            cred.setCredentials(
                new AuthScope(proxyHost), new UsernamePasswordCredentials(proxyUser, proxyPass));
            builder =
                builder
                    .setDefaultCredentialsProvider(cred)
                    .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
          }
        }
      }
    }

    return builder.build();
  }
예제 #5
0
  public static String sendHttpGet(
      String url, String ticket, int returnCodeIDP, int returnCodeRP, int idpPort)
      throws Exception {

    CloseableHttpClient httpClient = null;
    try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
      try {
        trustStore.load(instream, "clientpass".toCharArray());
      } finally {
        try {
          instream.close();
        } catch (Exception ex) {
          ex.printStackTrace();
        }
      }

      SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
      sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
      sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

      SSLContext sslContext = sslContextBuilder.build();
      SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

      HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
      httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
      httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

      httpClient = httpClientBuilder.build();

      HttpGet httpget = new HttpGet(url);
      httpget.addHeader("Authorization", "Negotiate " + ticket);

      HttpResponse response = httpClient.execute(httpget);
      HttpEntity entity = response.getEntity();

      System.out.println(response.getStatusLine());
      if (entity != null) {
        System.out.println("Response content length: " + entity.getContentLength());
      }
      Assert.assertTrue(
          "IDP HTTP Response code: "
              + response.getStatusLine().getStatusCode()
              + " [Expected: "
              + returnCodeIDP
              + "]",
          returnCodeIDP == response.getStatusLine().getStatusCode());

      if (response.getStatusLine().getStatusCode() != 200) {
        return null;
      }

      //            Redirect to a POST is not supported without user interaction
      //            http://www.ietf.org/rfc/rfc2616.txt
      //            If the 301 status code is received in response to a request other
      //            than GET or HEAD, the user agent MUST NOT automatically redirect the
      //            request unless it can be confirmed by the user, since this might
      //            change the conditions under which the request was issued.

      Source source = new Source(EntityUtils.toString(entity));
      List<NameValuePair> nvps = new ArrayList<NameValuePair>();
      FormFields formFields = source.getFormFields();

      List<Element> forms = source.getAllElements(HTMLElementName.FORM);
      Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size());
      String postUrl = forms.get(0).getAttributeValue("action");

      Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa"));
      Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult"));

      for (FormField formField : formFields) {
        if (formField.getUserValueCount() != 0) {
          nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0)));
        }
      }
      HttpPost httppost = new HttpPost(postUrl);
      httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

      response = httpClient.execute(httppost);

      entity = response.getEntity();
      System.out.println(response.getStatusLine());
      Assert.assertTrue(
          "RP HTTP Response code: "
              + response.getStatusLine().getStatusCode()
              + " [Expected: "
              + returnCodeRP
              + "]",
          returnCodeRP == response.getStatusLine().getStatusCode());

      if (entity != null) {
        System.out.println("Response content length: " + entity.getContentLength());
      }

      return EntityUtils.toString(entity);
    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      if (httpClient != null) {
        httpClient.close();
      }
    }
  }