public void init() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    ThreadSafeClientConnManager conMan = new ThreadSafeClientConnManager(schemeRegistry);
    conMan.setMaxTotal(maxTotalConnections);
    conMan.setDefaultMaxPerRoute(maxPerRouteConnections);

    httpClient = new DefaultHttpClient(conMan, clientParams);

    if (credentials != null) {
      CredentialsProvider credentialsProvider = httpClient.getCredentialsProvider();
      credentialsProvider.setCredentials(getAuthScope(), credentials);

      // preemptive basic auth hc 4.0 style
      if (authPreemptive) {
        BasicScheme basicAuth = new BasicScheme();
        httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(basicAuth), 0);
      }

      List<String> authpref = new ArrayList<String>();
      authpref.add(AuthPolicy.BASIC);
      // authpref.add(AuthPolicy.DIGEST);
      httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
    }

    if (sslSocketFactory != null) {
      SSLSocketFactory sslSf =
          new SSLSocketFactory(
              sslSocketFactory.getSSLContext(), SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
      Scheme https = new Scheme("https", 443, sslSf);
      schemeRegistry.register(https);
    }
  }
Esempio n. 2
0
    public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {

      AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

      if (authState.getAuthScheme() != null || authState.hasAuthOptions()) {
        return;
      }

      // If no authState has been established and this is a PUT or POST request, add preemptive
      // authorisation
      String requestMethod = request.getRequestLine().getMethod();
      if (requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) {
        CredentialsProvider credentialsProvider =
            (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        Credentials credentials =
            credentialsProvider.getCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()));
        if (credentials == null) {
          throw new HttpException("No credentials for preemptive authentication");
        }
        authState.update(authScheme, credentials);
      }
    }
  public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
        new AuthScope("localhost", 443), new UsernamePasswordCredentials("username", "password"));
    CloseableHttpClient httpclient =
        HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {
      HttpGet httpget = new HttpGet("https://localhost/protected");

      System.out.println("executing request" + httpget.getRequestLine());
      CloseableHttpResponse response = httpclient.execute(httpget);
      try {
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
          System.out.println("Response content length: " + entity.getContentLength());
        }
        EntityUtils.consume(entity);
      } finally {
        response.close();
      }
    } finally {
      httpclient.close();
    }
  }
Esempio n. 4
0
  protected CloseableHttpClient constructHttpClient() throws IOException {
    RequestConfig config =
        RequestConfig.custom()
            .setConnectTimeout(20 * 1000)
            .setConnectionRequestTimeout(20 * 1000)
            .setSocketTimeout(20 * 1000)
            .setMaxRedirects(20)
            .build();

    URL mmsc = new URL(apn.getMmsc());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();

    if (apn.hasAuthentication()) {
      credsProvider.setCredentials(
          new AuthScope(
              mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
          new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
    }

    return HttpClients.custom()
        .setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
        .setRedirectStrategy(new LaxRedirectStrategy())
        .setUserAgent("Android-Mms/2.0")
        .setConnectionManager(new BasicHttpClientConnectionManager())
        .setDefaultRequestConfig(config)
        .setDefaultCredentialsProvider(credsProvider)
        .build();
  }
Esempio n. 5
0
    public Builder setKerberosAuth(GSSCredentialProvider gssCrendentialProvider) {
      Credentials creds =
          new Credentials() {
            @Override
            public String getPassword() {
              return null;
            }

            @Override
            public Principal getUserPrincipal() {
              return null;
            }
          };
      CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
      credentialsProvider.setCredentials(
          new AuthScope(_host, _port, AuthScope.ANY_REALM, AuthSchemes.SPNEGO), creds);
      _httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

      AuthSchemeProvider authSchemaProvider =
          gssCrendentialProvider == null
              ? new SPNegoSchemeFactory(true)
              : new BasicSPNegoSchemeFactory(true, gssCrendentialProvider);

      _httpClientBuilder.setDefaultAuthSchemeRegistry(
          RegistryBuilder.<AuthSchemeProvider>create()
              .register(AuthSchemes.SPNEGO, authSchemaProvider)
              .build());
      return this;
    }
Esempio n. 6
0
 public Builder setUsernameAuth(String username, String password) {
   CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
   credentialsProvider.setCredentials(
       AuthScope.ANY, new UsernamePasswordCredentials(username, password));
   _httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
   return this;
 }
Esempio n. 7
0
 /**
  * It is convenient to be able to directly set the Credentials (not the provider) when those
  * credentials are fixed.
  *
  * @param creds
  * @param scope where to use it (i.e. on what host)
  * @throws HTTPException
  */
 public static void setGlobalCredentials(Credentials creds, AuthScope scope) throws HTTPException {
   assert (creds != null);
   if (scope == null) scope = AuthScope.ANY;
   CredentialsProvider provider = new BasicCredentialsProvider();
   provider.setCredentials(scope, creds);
   setGlobalCredentialsProvider(provider, scope);
 }
Esempio n. 8
0
    public void process(HttpRequest request, HttpContext context)
        throws HttpException, IOException {

      AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

      if (request.getFirstHeader("Authorization") != null) {
        // Using OAuth, leave as is
      } else if (request.getFirstHeader("X-No-Auth") != null) {
        // No auth required, leave as is
      } else {
        // If no auth scheme avaialble yet, try to initialize it preemptively
        if (authState.getAuthScheme() == null) {
          AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
          CredentialsProvider credsProvider =
              (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
          HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
          if (authScheme != null) {
            Credentials creds =
                credsProvider.getCredentials(
                    new AuthScope(targetHost.getHostName(), targetHost.getPort()));
            if (creds == null) {
              throw new HttpException("No credentials for preemptive authentication");
            } else {
              authState.setAuthScheme(authScheme);
              authState.setCredentials(creds);
            }
          }
        }
      }
    }
 /*.................................................................................................................*/
 public HttpClient getHttpClient() {
   // from http://www.artima.com/forums/flat.jsp?forum=121&thread=357685
   CredentialsProvider provider = new BasicCredentialsProvider();
   UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
   provider.setCredentials(AuthScope.ANY, credentials);
   return HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
 }
Esempio n. 10
0
    public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
      AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
      if (authState.getAuthScheme() != null) {
        return;
      }

      AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
      if (authScheme == null) {
        return;
      }

      CredentialsProvider credsProvider =
          (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
      HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

      Credentials creds =
          credsProvider.getCredentials(
              new AuthScope(targetHost.getHostName(), targetHost.getPort()));
      if (creds == null) {
        return;
      }

      authState.setAuthScheme(authScheme);
      authState.setCredentials(creds);
    }
  public void afterPropertiesSet() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setConnectionManager(getPoolingHttpClientConnectionManager());

    if ((_login != null) && (_password != null)) {
      CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

      credentialsProvider.setCredentials(
          new AuthScope(_hostName, _hostPort), new UsernamePasswordCredentials(_login, _password));

      httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
      httpClientBuilder.setRetryHandler(new HttpRequestRetryHandlerImpl());
    } else {
      if (_logger.isWarnEnabled()) {
        _logger.warn("Login and password are required");
      }
    }

    try {
      setProxyHost(httpClientBuilder);

      _closeableHttpClient = httpClientBuilder.build();

      if (_logger.isDebugEnabled()) {
        _logger.debug("Configured client for " + _protocol + "://" + _hostName);
      }
    } catch (Exception e) {
      _logger.error("Unable to configure client", e);
    }
  }
Esempio n. 12
0
 /**
  * It is convenient to be able to directly set the Credentials (not the provider) when those
  * credentials are fixed.
  *
  * @param creds
  * @param scope where to use it (i.e. on what host)
  * @throws HTTPException
  */
 public HTTPSession setCredentials(Credentials creds, AuthScope scope) throws HTTPException {
   assert (creds != null);
   if (scope == null) scope = AuthScope.ANY;
   CredentialsProvider provider = new BasicCredentialsProvider();
   provider.setCredentials(scope, creds);
   setCredentialsProvider(provider, scope);
   return this;
 }
Esempio n. 13
0
 @Deprecated
 public static void setGlobalCredentials(String url, Credentials creds) throws HTTPException {
   assert (url != null && creds != null);
   AuthScope scope = HTTPAuthUtil.uriToAuthScope(url);
   CredentialsProvider provider = new BasicCredentialsProvider();
   provider.setCredentials(scope, creds);
   setGlobalCredentialsProvider(provider, scope);
 }
Esempio n. 14
0
 @Override
 public HttpClientContext decoratePrototypeContext(
     AuthScope scope, SiteConfig location, PasswordType type, HttpClientContext ctx) {
   if (user != null) {
     final CredentialsProvider credProvider = new BasicCredentialsProvider();
     credProvider.setCredentials(scope, new UsernamePasswordCredentials(user, pass));
     ctx.setCredentialsProvider(credProvider);
   }
   return ctx;
 }
Esempio n. 15
0
 @Override
 public void authenticate() throws CommunicationException {
   LOGGER.debug(
       "Creating credentials provider with username: '******' and password: '******'", username, password);
   CredentialsProvider credsProvider = new BasicCredentialsProvider();
   credsProvider.setCredentials(
       new AuthScope(getTarget().getHostName(), getTarget().getPort(), null, authScheme),
       new UsernamePasswordCredentials(username, password));
   setCredentialsProvider(credsProvider);
   super.authenticate();
 }
Esempio n. 16
0
 public synchronized HttpClient getHttpClient() {
   checkDisposed();
   if (httpClient == null && authenticationInfo != null) {
     final Credentials credentials = AuthHelper.getCredentials(type, authenticationInfo);
     final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
     credentialsProvider.setCredentials(AuthScope.ANY, credentials);
     httpClient =
         HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
   }
   return httpClient;
 }
Esempio n. 17
0
  // 获得设置代理的httpClent实例
  private CloseableHttpClient getHttpClientWithProxy(HttpProxy proxy) {
    HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(
        new AuthScope(proxy.getHost(), proxy.getPort()),
        new UsernamePasswordCredentials(proxy.getUser(), proxy.getPassword()));

    return HttpClients.custom()
        .setProxy(proxyHost)
        .setDefaultCredentialsProvider(credentialsProvider)
        .build();
  }
Esempio n. 18
0
  @Test
  @JUnitHttpServer(
      port = 9162,
      basicAuth = true,
      webapps = {@Webapp(context = "/testContext", path = "src/test/resources/test-webapp")})
  public void testBasicAuthFailure() throws Exception {
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpUriRequest method = new HttpGet("http://localhost:9162/testContext/monkey");

    final CredentialsProvider cp = client.getCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "sucks");
    cp.setCredentials(new AuthScope("localhost", 9162), credentials);

    final HttpResponse response = client.execute(method);
    assertEquals(401, response.getStatusLine().getStatusCode());
  }
Esempio n. 19
0
  protected HttpClient getClient() {
    Credentials defaultcreds = new UsernamePasswordCredentials(this.token, "x");
    CredentialsProvider cp = new BasicCredentialsProvider();
    cp.setCredentials(new AuthScope(getHost(), -1, AuthScope.ANY_REALM), defaultcreds);
    HttpClientBuilder clientBuilder =
        HttpClients.custom()
            .setDefaultCredentialsProvider(cp)
            .setRedirectStrategy(new LaxRedirectStrategy());

    ProxyConfiguration proxy = Hudson.getInstance().proxy;
    if (proxy != null) {
      clientBuilder.setProxy(new HttpHost(proxy.name, proxy.port));
    }

    return clientBuilder.build();
  }
Esempio n. 20
0
  /**
   * Define the Credentials
   *
   * @param httpClientBuilder
   * @param url
   * @return
   * @throws java.net.MalformedURLException
   */
  private HttpClientBuilder configCredentials(HttpClientBuilder httpClientBuilder, final String url)
      throws DSSException {

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    for (final Map.Entry<HttpHost, UsernamePasswordCredentials> entry :
        authenticationMap.entrySet()) {

      final HttpHost httpHost = entry.getKey();
      final UsernamePasswordCredentials usernamePasswordCredentials = entry.getValue();
      credsProvider.setCredentials(
          new AuthScope(httpHost.getHostName(), httpHost.getPort()), usernamePasswordCredentials);
    }
    httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
    httpClientBuilder = configureProxy(httpClientBuilder, credsProvider, url);
    return httpClientBuilder;
  }
Esempio n. 21
0
  /**
   * @param argv host username password domain workstation
   * @throws IOException
   */
  public static void main(String[] argv) throws IOException {
    int status = -1;
    try {
      if (argv.length < 1) {
        return;
      }

      String path = argv[0];
      String username = "";
      String password = "";
      String domain = "";
      String workstation = "";

      if (argv.length > 2) {
        username = argv[1];
      }
      if (argv.length > 2) {
        password = argv[2];
      }

      if (argv.length > 3) {
        domain = argv[3];
      }

      if (argv.length > 4) {
        workstation = argv[4];
      }

      CloseableHttpClient client = HttpClients.createDefault();
      CredentialsProvider provider = new BasicCredentialsProvider();
      provider.setCredentials(
          AuthScope.ANY, new NTCredentials(username, password, workstation, domain));

      // HttpHost host = new HttpHost("10.130.163.112", 8081, "http");
      HttpClientContext context = HttpClientContext.create();
      context.setCredentialsProvider(provider);
      HttpGet get = new HttpGet(path);
      CloseableHttpResponse resp = client.execute(get, context);
      System.out.println(resp.getStatusLine());
      status = resp.getStatusLine().getStatusCode();
    } finally {

      System.out.println("status=" + status);
    }
  }
Esempio n. 22
0
  /**
   * Configure the proxy with the required credential if needed
   *
   * @param httpClientBuilder
   * @param credsProvider
   * @param url
   * @return
   * @throws java.net.MalformedURLException
   */
  private HttpClientBuilder configureProxy(
      HttpClientBuilder httpClientBuilder, CredentialsProvider credsProvider, String url)
      throws DSSException {

    try {

      if (proxyPreferenceManager == null) {
        return httpClientBuilder;
      }
      final String protocol = new URL(url).getProtocol();

      final boolean proxyHTTPS =
          Protocol.isHttps(protocol) && proxyPreferenceManager.isHttpsEnabled();
      final boolean proxyHTTP = Protocol.isHttp(protocol) && proxyPreferenceManager.isHttpEnabled();

      if (!proxyHTTPS && !proxyHTTP) {
        return httpClientBuilder;
      }

      String proxyHost = null;
      int proxyPort = 0;
      String proxyUser = null;
      String proxyPassword = null;

      if (proxyHTTPS) {
        LOG.debug("Use proxy https parameters");
        final Long port = proxyPreferenceManager.getHttpsPort();
        proxyPort = port != null ? port.intValue() : 0;
        proxyHost = proxyPreferenceManager.getHttpsHost();
        proxyUser = proxyPreferenceManager.getHttpsUser();
        proxyPassword = proxyPreferenceManager.getHttpsPassword();
      } else // noinspection ConstantConditions
      if (proxyHTTP) {
        LOG.debug("Use proxy http parameters");
        final Long port = proxyPreferenceManager.getHttpPort();
        proxyPort = port != null ? port.intValue() : 0;
        proxyHost = proxyPreferenceManager.getHttpHost();
        proxyUser = proxyPreferenceManager.getHttpUser();
        proxyPassword = proxyPreferenceManager.getHttpPassword();
      }

      if (DSSUtils.isNotEmpty(proxyUser) && DSSUtils.isNotEmpty(proxyPassword)) {
        LOG.debug("proxy user: "******":" + proxyPassword);
        AuthScope proxyAuth = new AuthScope(proxyHost, proxyPort);
        UsernamePasswordCredentials proxyCredentials =
            new UsernamePasswordCredentials(proxyUser, proxyPassword);
        credsProvider.setCredentials(proxyAuth, proxyCredentials);
      }

      LOG.debug("proxy host/port: " + proxyHost + ":" + proxyPort);
      // TODO SSL peer shut down incorrectly when protocol is https
      HttpHost proxy = new HttpHost(proxyHost, proxyPort, Protocol.HTTP.getName());
      return httpClientBuilder.setProxy(proxy);
    } catch (MalformedURLException e) {
      throw new DSSException(e);
    }
  }
  public HttpResponse executeBinaryHttpRequest(HttpUriRequest request, int expectedStatusCode) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("kermit", "kermit");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    try {
      HttpResponse response = client.execute(request);
      Assert.assertNotNull(response.getStatusLine());
      Assert.assertEquals(expectedStatusCode, response.getStatusLine().getStatusCode());
      return response;

    } catch (ClientProtocolException e) {
      Assert.fail(e.getMessage());
    } catch (IOException e) {
      Assert.fail(e.getMessage());
    }
    return null;
  }
Esempio n. 24
0
  private ElasticsearchClient(List<Node> nodes, String username, String password) {
    List<HttpHost> hosts = new ArrayList<>(nodes.size());
    for (Node node : nodes) {
      hosts.add(new HttpHost(node.getHost(), node.getPort(), node.getScheme().toLowerCase()));
    }
    RestClientBuilder builder = RestClient.builder(hosts.toArray(new HttpHost[hosts.size()]));

    if (username != null) {
      CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
      credentialsProvider.setCredentials(
          AuthScope.ANY, new UsernamePasswordCredentials(username, password));
      builder.setHttpClientConfigCallback(
          httpClientBuilder ->
              httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
    }

    client = builder.build();
  }
 /**
  * Instantiates a new digest authentication client wrapper.
  *
  * @param hostname the hostname
  * @param port the port
  * @param scheme the scheme
  * @param username the username
  * @param password the password
  */
 public DigestAuthenticationClientWrapper(
     String hostname, int port, String scheme, String username, String password) {
   // logger.trace("==== DigestAuthenticationHttpClientWrapper ENTRY ========");
   target = new HttpHost(hostname, port, scheme);
   credsProvider = new BasicCredentialsProvider();
   credsProvider.setCredentials(
       new AuthScope(target.getHostName(), target.getPort()),
       new UsernamePasswordCredentials(username, password));
   logger.fine("==== DigestAuthenticationHttpClientWrapper EXIT ========");
 }
  public void process(final HttpRequest request, final HttpContext context)
      throws HttpException, IOException {

    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

    // If no auth scheme avaialble yet, try to initialize it preemptively
    if (authState.getAuthScheme() == null) {
      CredentialsProvider credsProvider =
          (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
      HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
      Credentials creds =
          credsProvider.getCredentials(
              new AuthScope(targetHost.getHostName(), targetHost.getPort()));
      if (creds == null) {
        throw new HttpException("No credentials for preemptive authentication");
      }
      authState.setAuthScheme(authScheme);
      authState.setCredentials(creds);
    }
  }
Esempio n. 27
0
    public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {

      AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
      CredentialsProvider credsProvider =
          (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
      HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

      // If not auth scheme has been initialized yet
      if (authState.getAuthScheme() == null) {
        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        // Obtain credentials matching the target host
        Credentials creds = credsProvider.getCredentials(authScope);
        // If found, generate BasicScheme preemptively
        if (creds != null) {
          authState.setAuthScheme(new BasicScheme());
          authState.setCredentials(creds);
        }
      }
    }
 protected ClientRequest newRequest(String uriString) {
   URI uri;
   try {
     uri = new URI(uriString);
   } catch (URISyntaxException e) {
     throw new RuntimeException("Malformed request URI was specified: '" + uriString + "'!", e);
   }
   if (TestConfig.isLocalServer()) {
     return new ClientRequest(uriString);
   } else {
     CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
     credentialsProvider.setCredentials(
         new AuthScope(uri.getHost(), uri.getPort()),
         new UsernamePasswordCredentials(TestConfig.getUsername(), TestConfig.getPassword()));
     HttpClient client =
         HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
     ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(client);
     return new ClientRequest(uriString, executor);
   }
 }
Esempio n. 29
0
  @Test
  @JUnitHttpServer(
      port = 9162,
      basicAuth = true,
      webapps = {@Webapp(context = "/testContext", path = "src/test/resources/test-webapp")})
  public void testBasicAuthSuccess() throws Exception {
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpUriRequest method = new HttpGet("http://localhost:9162/testContext/monkey");

    final CredentialsProvider cp = client.getCredentialsProvider();
    final UsernamePasswordCredentials credentials =
        new UsernamePasswordCredentials("admin", "istrator");
    cp.setCredentials(new AuthScope("localhost", 9162), credentials);

    final HttpResponse response = client.execute(method);
    final String responseString = EntityUtils.toString(response.getEntity());
    LogUtils.debugf(this, "got response:\n%s", responseString);
    assertEquals(200, response.getStatusLine().getStatusCode());
    assertTrue(responseString.contains("You are reading this from a servlet!"));
  }
Esempio n. 30
0
  protected static ClientConfig getClientConfig(
      final Type type,
      final AuthenticationInfo authenticationInfo,
      final boolean includeProxySettings) {
    final Credentials credentials = AuthHelper.getCredentials(type, authenticationInfo);

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);

    final ConnectorProvider connectorProvider = new ApacheConnectorProvider();

    final ClientConfig clientConfig = new ClientConfig().connectorProvider(connectorProvider);
    clientConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);

    clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true);
    clientConfig.property(
        ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

    // Define fiddler as a local HTTP proxy
    if (includeProxySettings) {
      final String proxyHost;
      if (System.getProperty("proxyHost") != null) {
        proxyHost = System.getProperty("proxyHost");
      } else {
        proxyHost = "127.0.0.1";
      }

      final String proxyPort;
      if (System.getProperty("proxyPort") != null) {
        proxyPort = System.getProperty("proxyPort");
      } else {
        proxyPort = "8888";
      }

      final String proxyUrl = String.format("http://%s:%s", proxyHost, proxyPort);

      clientConfig.property(ClientProperties.PROXY_URI, proxyUrl);
      clientConfig.property(ApacheClientProperties.SSL_CONFIG, getSslConfigurator());
    }
    return clientConfig;
  }