@Test
  public void testBasicAuthenticationNoCreds() throws Exception {
    this.localServer.register("*", new AuthHandler());
    this.localServer.start();

    TestCredentialsProvider credsProvider = new TestCredentialsProvider(null);

    this.httpclient.setCredentialsProvider(credsProvider);

    HttpGet httpget = new HttpGet("/");

    HttpResponse response = this.httpclient.execute(getServerHttp(), httpget);
    HttpEntity entity = response.getEntity();
    Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity);
    EntityUtils.consume(entity);
    AuthScope authscope = credsProvider.getAuthScope();
    Assert.assertNotNull(authscope);
    Assert.assertEquals("test realm", authscope.getRealm());
  }
  @Test
  public void testBasicAuthenticationSuccess() throws Exception {
    this.serverBootstrap.registerHandler("*", new AuthHandler());

    final HttpHost target = start();

    final HttpClientContext context = HttpClientContext.create();
    final TestCredentialsProvider credsProvider =
        new TestCredentialsProvider(new UsernamePasswordCredentials("test", "test"));
    context.setCredentialsProvider(credsProvider);
    final HttpGet httpget = new HttpGet("/");

    final HttpResponse response = this.httpclient.execute(target, httpget, context);
    final HttpEntity entity = response.getEntity();
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity);
    EntityUtils.consume(entity);
    final AuthScope authscope = credsProvider.getAuthScope();
    Assert.assertNotNull(authscope);
    Assert.assertEquals("test realm", authscope.getRealm());
  }
  @Test
  public void testBasicAuthenticationSuccessOnRepeatablePost() throws Exception {
    this.localServer.register("*", new AuthHandler());
    this.localServer.start();

    TestCredentialsProvider credsProvider =
        new TestCredentialsProvider(new UsernamePasswordCredentials("test", "test"));

    this.httpclient.setCredentialsProvider(credsProvider);

    HttpPost httppost = new HttpPost("/");
    httppost.setEntity(new StringEntity("some important stuff", Consts.ASCII));

    HttpResponse response = this.httpclient.execute(getServerHttp(), httppost);
    HttpEntity entity = response.getEntity();
    Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity);
    EntityUtils.consume(entity);
    AuthScope authscope = credsProvider.getAuthScope();
    Assert.assertNotNull(authscope);
    Assert.assertEquals("test realm", authscope.getRealm());
  }
示例#4
0
  public DataField[] registerAndGetStructure() throws IOException, ClassNotFoundException {
    // Create the POST request
    HttpPost httpPost =
        new HttpPost(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp));
    // Add the POST parameters
    httpPost.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8));
    //
    httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
    // Create local execution context
    HttpContext localContext = new BasicHttpContext();
    //
    NotificationRegistry.getInstance().addNotification(uid, this);
    int tries = 0;
    AuthState authState = null;
    //
    while (tries < 2) {
      tries++;
      HttpResponse response = null;
      try {
        // Execute the POST request
        response = httpclient.execute(httpPost, localContext);
        //
        int sc = response.getStatusLine().getStatusCode();
        //
        if (sc == HttpStatus.SC_OK) {
          logger.debug(
              new StringBuilder()
                  .append("Wants to consume the structure packet from ")
                  .append(initParams.getRemoteContactPoint())
                  .toString());
          structure = (DataField[]) XSTREAM.fromXML(response.getEntity().getContent());
          logger.debug("Connection established for: " + initParams.getRemoteContactPoint());
          break;
        } else {
          if (sc == HttpStatus.SC_UNAUTHORIZED)
            authState =
                (AuthState)
                    localContext.getAttribute(
                        ClientContext.TARGET_AUTH_STATE); // Target host authentication required
          else if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
            authState =
                (AuthState)
                    localContext.getAttribute(
                        ClientContext.PROXY_AUTH_STATE); // Proxy authentication required
          else {
            logger.error(
                new StringBuilder()
                    .append("Unexpected POST status code returned: ")
                    .append(sc)
                    .append("\nreason: ")
                    .append(response.getStatusLine().getReasonPhrase())
                    .toString());
          }
          if (authState != null) {
            if (initParams.getUsername() == null
                || (tries > 1 && initParams.getUsername() != null)) {
              logger.error(
                  "A valid username/password required to connect to the remote host: "
                      + initParams.getRemoteContactPoint());
            } else {

              AuthScope authScope = authState.getAuthScope();
              logger.warn(
                  new StringBuilder()
                      .append("Setting Credentials for host: ")
                      .append(authScope.getHost())
                      .append(":")
                      .append(authScope.getPort())
                      .toString());
              Credentials creds =
                  new UsernamePasswordCredentials(
                      initParams.getUsername(), initParams.getPassword());
              httpclient.getCredentialsProvider().setCredentials(authScope, creds);
            }
          }
        }
      } catch (RuntimeException ex) {
        // In case of an unexpected exception you may want to abort
        // the HTTP request in order to shut down the underlying
        // connection and release it back to the connection manager.
        logger.warn("Aborting the HTTP POST request.");
        httpPost.abort();
        throw ex;
      } finally {
        if (response != null && response.getEntity() != null) {
          response.getEntity().consumeContent();
        }
      }
    }

    if (structure == null) throw new RuntimeException("Cannot connect to the remote host.");

    return structure;
  }
示例#5
0
    public Credentials getCredentials(final AuthScope authScope) {
      if (authScope == null) {
        throw new IllegalArgumentException("Authentication scope may not be null");
      }

      //	if( cache.containsKey( authScope ) )
      //	{
      //	return cache.get( authScope );
      //	}

      String pw = getPassword();
      if (pw == null) pw = "";

      if (AuthPolicy.NTLM.equalsIgnoreCase(authScope.getScheme())
          || AuthPolicy.SPNEGO.equalsIgnoreCase(authScope.getScheme())) {
        String workstation = "";
        try {
          workstation = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
        }

        if (hasCredentials()) {
          log.info("Returning url credentials");
          return new NTCredentials(getUsername(), pw, workstation, null);
        }

        log.info(
            authScope.getHost() + ":" + authScope.getPort() + " requires Windows authentication");
        if (ntDialog == null) {
          buildNtDialog();
        }

        StringToStringMap values = new StringToStringMap();
        values.put(
            "Info",
            "Authentication required for ["
                + authScope.getHost()
                + ":"
                + authScope.getPort()
                + "]");
        ntDialog.setValues(values);

        if (ntDialog.show()) {
          values = ntDialog.getValues();
          NTCredentials credentials =
              new NTCredentials(
                  values.get("Username"),
                  values.get("Password"),
                  workstation,
                  values.get("Domain"));

          cache.put(authScope, credentials);
          return credentials;
        }
      } else if (AuthPolicy.BASIC.equalsIgnoreCase(authScope.getScheme())
          || AuthPolicy.DIGEST.equalsIgnoreCase(authScope.getScheme())) {
        if (hasCredentials()) {
          log.info("Returning url credentials");
          UsernamePasswordCredentials credentials =
              new UsernamePasswordCredentials(getUsername(), pw);
          cache.put(authScope, credentials);
          return credentials;
        }

        log.info(
            authScope.getHost()
                + ":"
                + authScope.getPort()
                + " requires authentication with the realm '"
                + authScope.getRealm()
                + "'");
        ShowDialog showDialog = new ShowDialog();
        showDialog.values.put(
            "Info",
            "Authentication required for ["
                + authScope.getHost()
                + ":"
                + authScope.getPort()
                + "]");

        UISupport.getUIUtils().runInUIThreadIfSWT(showDialog);
        if (showDialog.result) {
          UsernamePasswordCredentials credentials =
              new UsernamePasswordCredentials(
                  showDialog.values.get("Username"), showDialog.values.get("Password"));
          cache.put(authScope, credentials);
          return credentials;
        }
      }

      return null;
    }