@Test
  public void testConnectionBasedAuthOnlyIfChallenged() throws Exception {
    HttpRequest request = new BasicHttpRequest("GET", "/");
    HttpContext context = new BasicHttpContext();

    AuthState authstate = new AuthState();

    BasicScheme authscheme =
        new BasicScheme() {

          @Override
          public boolean isConnectionBased() {
            return true;
          }
        };

    BasicHeader challenge = new BasicHeader(AUTH.WWW_AUTH, "BASIC realm=auth-realm");
    authscheme.processChallenge(challenge);

    Credentials creds = new UsernamePasswordCredentials("user", "secret");

    authstate.setState(AuthProtocolState.SUCCESS);
    authstate.update(authscheme, creds);

    context.setAttribute(ClientContext.TARGET_AUTH_STATE, authstate);

    HttpRequestInterceptor interceptor = new RequestTargetAuthentication();
    interceptor.process(request, context);
    Header header = request.getFirstHeader(AUTH.WWW_AUTH_RESP);
    Assert.assertNull(header);
  }
Esempio n. 2
0
        public void process(final HttpRequest request, final HttpContext context)
            throws HttpException, IOException {
          Locale locale = Locale.getDefault();
          request.setHeader(
              "Accept-Language", (locale.getLanguage() + "-" + locale.getCountry()).toLowerCase());
          request.setHeader("Accept-Encoding", "gzip");
          AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
          // HttpHost targetHost = (HttpHost)
          // context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
          if (true /*(INFO.HOST_IP.equals(targetHost.getHostName())) && (INFO.HOST_PORT == targetHost.getPort())*/) {
            authState.setAuthScheme(new BasicScheme());

            /* username = "******";
            password = "******";*/
            if (username == null) {
              //            		username = appContext.getSharedPreferences(BaseActivity.SETTING_INFOS,
              // Context.MODE_PRIVATE).getString(BaseActivity.NAME, null);
              //            		password = appContext.getSharedPreferences(BaseActivity.SETTING_INFOS,
              // Context.MODE_PRIVATE).getString(BaseActivity.PASSWORD, null);
            }
            // INFO.Log("username", username+"");
            if (username != null) {
              authState.setCredentials(new UsernamePasswordCredentials(username, password));
            }
          }
        }
Esempio n. 3
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);
    }
Esempio n. 4
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);
            }
          }
        }
      }
    }
Esempio n. 5
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);
      }
    }
  @Override
  public void process(final HttpRequest request, final HttpContext context)
      throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

    if (authState.getAuthScheme() == null) {
      Credentials creds = new UsernamePasswordCredentials(myUsername, myPassword);
      authState.update(new BasicScheme(), creds);
    }
  }
 public void process(final HttpResponse response, final HttpContext context)
     throws HttpException, IOException {
   AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
   if (authState != null) {
     AuthScheme authScheme = authState.getAuthScheme();
     // Stick the auth scheme to the local context, so
     // we could try to authenticate subsequent requests
     // preemptively
     if (authScheme instanceof DigestScheme) {
       context.setAttribute("preemptive-auth", authScheme);
     }
   }
 }
Esempio n. 8
0
  static void testProtectedResource() throws ClientProtocolException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpclient.execute(httpget, localContext);

    AuthState proxyAuthState =
        (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);

    System.out.println("Proxy auth scope: " + proxyAuthState.getAuthScope());
    System.out.println("Proxy auth scheme: " + proxyAuthState.getAuthScheme());
    System.out.println("Proxy auth credentials: " + proxyAuthState.getCredentials());

    AuthState targetAuthState =
        (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
    System.out.println("Target auth scope: " + targetAuthState.getAuthScope());
    System.out.println("Target auth scheme: " + targetAuthState.getAuthScheme());
    System.out.println("Target auth credentials: " + targetAuthState.getCredentials());

    HttpEntity entity = response.getEntity();
    String charset = HttpclientTutorial.getResponseCharset(response);
    System.out.println("charset:" + charset);
    HttpclientTutorial.output(entity, charset);

    EntityUtils.consume(entity);
  }
  @Test
  public void testExecEntityEnclosingRequestRetryOnAuthChallenge() throws Exception {
    final HttpRoute route = new HttpRoute(target);
    final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test"));
    final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?");
    final InputStream instream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3}));
    response1.setEntity(EntityBuilder.create().setStream(instream1).build());
    final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
    final InputStream instream2 = Mockito.spy(new ByteArrayInputStream(new byte[] {2, 3, 4}));
    response2.setEntity(EntityBuilder.create().setStream(instream2).build());

    final AuthState proxyAuthState = new AuthState();
    proxyAuthState.setState(AuthProtocolState.SUCCESS);
    proxyAuthState.update(new NTLMScheme(), new NTCredentials("user:pass"));

    final HttpClientContext context = new HttpClientContext();
    context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxyAuthState);

    Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE);
    Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE);
    Mockito.when(
            requestExecutor.execute(
                Mockito.same(request),
                Mockito.<HttpClientConnection>any(),
                Mockito.<HttpClientContext>any()))
        .thenReturn(response1, response2);
    Mockito.when(
            reuseStrategy.keepAlive(Mockito.<HttpResponse>any(), Mockito.<HttpClientContext>any()))
        .thenReturn(Boolean.FALSE);
    Mockito.when(
            targetAuthStrategy.isAuthenticationRequested(
                Mockito.eq(target), Mockito.same(response1), Mockito.<HttpClientContext>any()))
        .thenReturn(Boolean.TRUE);

    final CloseableHttpResponse finalResponse =
        mainClientExec.execute(route, request, context, execAware);
    Mockito.verify(requestExecutor, Mockito.times(2)).execute(request, managedConn, context);
    Mockito.verify(managedConn).close();
    Mockito.verify(instream2, Mockito.never()).close();

    Assert.assertNotNull(finalResponse);
    Assert.assertEquals(200, finalResponse.getStatusLine().getStatusCode());
    Assert.assertNull(proxyAuthState.getAuthScheme());
    Assert.assertNull(proxyAuthState.getCredentials());
  }
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);
      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);
        }
      }
    }
  @Test
  public void testNoTargetAuthForConnectRequests() throws Exception {
    HttpRequest request = new BasicHttpRequest("CONNECT", "www.somedomain.com");
    HttpContext context = new BasicHttpContext();

    BasicScheme authscheme = new BasicScheme();
    Credentials creds = new UsernamePasswordCredentials("user", "secret");
    BasicHeader challenge = new BasicHeader(AUTH.WWW_AUTH, "BASIC realm=auth-realm");
    authscheme.processChallenge(challenge);

    AuthState authstate = new AuthState();
    authstate.update(authscheme, creds);

    context.setAttribute(ClientContext.TARGET_AUTH_STATE, authstate);

    HttpRequestInterceptor interceptor = new RequestTargetAuthentication();
    interceptor.process(request, context);
    Header header = request.getFirstHeader(AUTH.WWW_AUTH_RESP);
    Assert.assertNull(header);
  }
  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);
    }
  }
  @Test
  public void testTargetAuth() throws Exception {
    HttpRequest request = new BasicHttpRequest("GET", "/");
    HttpContext context = new BasicHttpContext();

    BasicScheme authscheme = new BasicScheme();
    Credentials creds = new UsernamePasswordCredentials("user", "secret");
    BasicHeader challenge = new BasicHeader(AUTH.WWW_AUTH, "BASIC realm=auth-realm");
    authscheme.processChallenge(challenge);

    AuthState authstate = new AuthState();
    authstate.update(authscheme, creds);

    context.setAttribute(ClientContext.TARGET_AUTH_STATE, authstate);

    HttpRequestInterceptor interceptor = new RequestTargetAuthentication();
    interceptor.process(request, context);
    Header header = request.getFirstHeader(AUTH.WWW_AUTH_RESP);
    Assert.assertNotNull(header);
    Assert.assertEquals("Basic dXNlcjpzZWNyZXQ=", header.getValue());
  }
Esempio n. 14
0
  private void updateAuthState(
      final AuthState authState, final HttpHost host, final CredentialsProvider credsProvider) {

    if (!authState.isValid()) {
      return;
    }

    String hostname = host.getHostName();
    int port = host.getPort();
    if (port < 0) {
      Scheme scheme = connManager.getSchemeRegistry().getScheme(host);
      port = scheme.getDefaultPort();
    }

    AuthScheme authScheme = authState.getAuthScheme();
    AuthScope authScope =
        new AuthScope(hostname, port, authScheme.getRealm(), authScheme.getSchemeName());

    if (this.log.isDebugEnabled()) {
      this.log.debug("Authentication scope: " + authScope);
    }
    Credentials creds = authState.getCredentials();
    if (creds == null) {
      creds = credsProvider.getCredentials(authScope);
      if (this.log.isDebugEnabled()) {
        if (creds != null) {
          this.log.debug("Found credentials");
        } else {
          this.log.debug("Credentials not found");
        }
      }
    } else {
      if (authScheme.isComplete()) {
        this.log.debug("Authentication failed");
        creds = null;
      }
    }
    authState.setAuthScope(authScope);
    authState.setCredentials(creds);
  }
Esempio n. 15
0
  private void processChallenges(
      final Map<String, Header> challenges,
      final AuthState authState,
      final AuthenticationHandler authHandler,
      final HttpResponse response,
      final HttpContext context)
      throws MalformedChallengeException, AuthenticationException {

    AuthScheme authScheme = authState.getAuthScheme();
    if (authScheme == null) {
      // Authentication not attempted before
      authScheme = authHandler.selectScheme(challenges, response, context);
      authState.setAuthScheme(authScheme);
    }
    String id = authScheme.getSchemeName();

    Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
    if (challenge == null) {
      throw new AuthenticationException(id + " authorization challenge expected, but not found");
    }
    authScheme.processChallenge(challenge);
    this.log.debug("Authorization challenge processed");
  }
Esempio n. 16
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;
  }