/** Configure the httpclient for use in all requests. */
  private void configureHttpClient(final DefaultHttpClient httpclient)
      throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException,
          UnrecoverableKeyException {

    configureTrust(httpclient);

    configureAuthentication(httpclient, BASIC, new BasicUserPrincipal(username));

    if (enableKerberos) {
      if (kerberosUseHttpSpn) {
        httpclient
            .getAuthSchemes()
            .register(KERBEROS, new KerberosSchemeFactory(!kerberosAddPortToSpn));
        httpclient
            .getAuthSchemes()
            .register(SPNEGO, new SPNegoSchemeFactory(!kerberosAddPortToSpn));
      } else {
        httpclient
            .getAuthSchemes()
            .register(KERBEROS, new WsmanKerberosSchemeFactory(!kerberosAddPortToSpn));
        httpclient
            .getAuthSchemes()
            .register(SPNEGO, new WsmanSPNegoSchemeFactory(!kerberosAddPortToSpn));
      }
      configureAuthentication(httpclient, KERBEROS, new KerberosPrincipal(username));
      configureAuthentication(httpclient, SPNEGO, new KerberosPrincipal(username));
    }

    httpclient.getParams().setBooleanParameter(HANDLE_AUTHENTICATION, true);
  }
  protected void initHttpClient(boolean useSpnego) {
    if (client != null) {
      after();
    }

    DefaultHttpClient httpClient = (DefaultHttpClient) new HttpClientBuilder().build();
    httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, spnegoSchemeFactory);

    if (useSpnego) {
      Credentials fake =
          new Credentials() {

            public String getPassword() {
              return null;
            }

            public Principal getUserPrincipal() {
              return null;
            }
          };

      httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, -1, null), fake);
    }

    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
    client = new ResteasyClientBuilder().httpEngine(engine).build();
  }
  /**
   * Get's an SSO Uri or null if there are any errors
   *
   * @return SSO uri or null
   */
  protected Uri doGetSSO() {

    if (user == null || pass == null) {
      return null;
    }

    DefaultHttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, App.userAgent);
    // register ntlm auth scheme
    client.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
    client
        .getCredentialsProvider()
        .setCredentials(
            // Limit the credentials only to the specified domain and port
            new AuthScope("portal.myfanshawe.ca", -1),
            // Specify credentials, most of the time only user/pass is needed
            new NTCredentials(user, pass, "", ""));

    final String[] ssoUrl = {null};
    final RedirectHandler defaultHandler = client.getRedirectHandler();
    client.setRedirectHandler(
        new RedirectHandler() {
          @Override
          public boolean isRedirectRequested(HttpResponse httpResponse, HttpContext httpContext) {
            Log.i(TAG, "isRedirectRequested");
            for (Header header : httpResponse.getAllHeaders()) {
              String name = header.getName();
              String value = header.getValue();
              if ("Location".equals(name)) {
                ssoUrl[0] = value;
              }
            }
            return false;
          }

          @Override
          public URI getLocationURI(HttpResponse httpResponse, HttpContext httpContext)
              throws ProtocolException {
            return defaultHandler.getLocationURI(httpResponse, httpContext);
          }
        });

    HttpGet folSSO = new HttpGet(requestURL);

    try {
      HttpResponse response = client.execute(folSSO);
      HttpEntity entity = response.getEntity();
      entity.consumeContent();
      Log.i(TAG, "SSO OK");
    } catch (IOException e) {
      return null;
    }

    if (ssoUrl[0] == null) {
      return null;
    }
    return Uri.parse(ssoUrl[0]);
  }
 protected HttpClient createHttpClient() {
   DefaultHttpClient client = new DefaultHttpClient(createClientConnectionManager());
   client.getAuthSchemes().register("Negotiate", new CustomSPNegoSchemeFactory());
   client
       .getCredentialsProvider()
       .setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
   final HttpParams httpParams = new BasicHttpParams();
   HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_CONNECTION_TIMEOUT);
   HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_CONNECTION_TIMEOUT);
   client.setParams(httpParams);
   return client;
 }
  public static void main(String[] args) throws Exception {

    System.setProperty("java.security.auth.login.config", "login.conf");
    System.setProperty("java.security.krb5.conf", "krb5.conf");
    System.setProperty("sun.security.krb5.debug", "true");
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    DefaultHttpClient httpclient = new DefaultHttpClient();

    NegotiateSchemeFactory nsf = new NegotiateSchemeFactory();
    //        nsf.setStripPort(false);
    //        nsf.setSpengoGenerator(new BouncySpnegoTokenGenerator());

    httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, nsf);

    Credentials use_jaas_creds =
        new Credentials() {

          public String getPassword() {
            return null;
          }

          public Principal getUserPrincipal() {
            return null;
          }
        };

    httpclient
        .getCredentialsProvider()
        .setCredentials(new AuthScope(null, -1, null), use_jaas_creds);

    HttpUriRequest request = new HttpGet("http://kerberoshost/");
    HttpResponse response = httpclient.execute(request);
    HttpEntity entity = response.getEntity();

    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    System.out.println("----------------------------------------");
    if (entity != null) {
      System.out.println(EntityUtils.toString(entity));
    }
    System.out.println("----------------------------------------");

    // This ensures the connection gets released back to the manager
    if (entity != null) {
      entity.consumeContent();
    }

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
  }
Beispiel #6
0
  /**
   * Creates request against SPNEGO protected web-app with FORM fallback. It tries to login using
   * SPNEGO first - if it fails, FORM is used.
   *
   * @param contextUrl
   * @param page
   * @param user
   * @param pass
   * @param expectedStatusCode
   * @return
   * @throws IOException
   * @throws URISyntaxException
   * @throws PrivilegedActionException
   * @throws LoginException
   */
  public static String makeHttpCallWithFallback(
      final String contextUrl,
      final String page,
      final String user,
      final String pass,
      final int expectedStatusCode)
      throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    final String strippedContextUrl = StringUtils.stripEnd(contextUrl, "/");
    final String url = strippedContextUrl + page;
    LOGGER.info("Requesting URL: " + url);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setRedirectStrategy(REDIRECT_STRATEGY);
    String unauthorizedPageBody = null;
    try {
      httpClient
          .getAuthSchemes()
          .register(AuthPolicy.SPNEGO, new JBossNegotiateSchemeFactory(true));
      httpClient
          .getCredentialsProvider()
          .setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());

      final HttpGet httpGet = new HttpGet(url);
      final HttpResponse response = httpClient.execute(httpGet);
      int statusCode = response.getStatusLine().getStatusCode();
      if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
        assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
        return EntityUtils.toString(response.getEntity());
      }
      final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
      assertTrue(
          "WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
      final Set<String> authnHeaderValues = new HashSet<String>();
      for (final Header header : authnHeaders) {
        authnHeaderValues.add(header.getValue());
      }
      assertTrue(
          "WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));

      LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
      unauthorizedPageBody = EntityUtils.toString(response.getEntity());

      // Use our custom configuration to avoid reliance on external config
      Configuration.setConfiguration(new Krb5LoginConfiguration());
      // 1. Authenticate to Kerberos.
      final LoginContext lc =
          new LoginContext(Utils.class.getName(), new UsernamePasswordHandler(user, pass));
      lc.login();

      // 2. Perform the work as authenticated Subject.
      final String responseBody =
          Subject.doAs(
              lc.getSubject(),
              new PrivilegedExceptionAction<String>() {
                public String run() throws Exception {
                  final HttpResponse response = httpClient.execute(httpGet);
                  int statusCode = response.getStatusLine().getStatusCode();
                  assertEquals(
                      "Unexpected status code returned after the authentication.",
                      expectedStatusCode,
                      statusCode);
                  return EntityUtils.toString(response.getEntity());
                }
              });
      lc.logout();
      return responseBody;
    } catch (LoginException e) {
      assertNotNull(unauthorizedPageBody);
      assertTrue(unauthorizedPageBody.contains("j_security_check"));

      HttpPost httpPost = new HttpPost(strippedContextUrl + "/j_security_check");
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
      nameValuePairs.add(new BasicNameValuePair("j_username", user));
      nameValuePairs.add(new BasicNameValuePair("j_password", pass));
      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      final HttpResponse response = httpClient.execute(httpPost);
      int statusCode = response.getStatusLine().getStatusCode();
      assertEquals(
          "Unexpected status code returned after the authentication.",
          expectedStatusCode,
          statusCode);
      return EntityUtils.toString(response.getEntity());
    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpClient.getConnectionManager().shutdown();
    }
  }
Beispiel #7
0
  /**
   * Returns response body for the given URL request as a String. It also checks if the returned
   * HTTP status code is the expected one. If the server returns {@link
   * HttpServletResponse#SC_UNAUTHORIZED} and an username is provided, then the given user is
   * authenticated against Kerberos and a new request is executed under the new subject.
   *
   * @param uri URI to which the request should be made
   * @param user Username
   * @param pass Password
   * @param expectedStatusCode expected status code returned from the requested server
   * @return HTTP response body
   * @throws IOException
   * @throws URISyntaxException
   * @throws PrivilegedActionException
   * @throws LoginException
   */
  public static String makeCallWithKerberosAuthn(
      final URI uri, final String user, final String pass, final int expectedStatusCode)
      throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    LOGGER.info("Requesting URI: " + uri);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
      httpClient
          .getAuthSchemes()
          .register(AuthPolicy.SPNEGO, new JBossNegotiateSchemeFactory(true));
      httpClient
          .getCredentialsProvider()
          .setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());

      final HttpGet httpGet = new HttpGet(uri);
      final HttpResponse response = httpClient.execute(httpGet);
      int statusCode = response.getStatusLine().getStatusCode();
      if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
        assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
        return EntityUtils.toString(response.getEntity());
      }
      final HttpEntity entity = response.getEntity();
      final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
      assertTrue(
          "WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
      final Set<String> authnHeaderValues = new HashSet<String>();
      for (final Header header : authnHeaders) {
        authnHeaderValues.add(header.getValue());
      }
      assertTrue(
          "WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));

      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
      }
      if (entity != null) EntityUtils.consume(entity);

      // Use our custom configuration to avoid reliance on external config
      Configuration.setConfiguration(new Krb5LoginConfiguration());
      // 1. Authenticate to Kerberos.
      final LoginContext lc =
          new LoginContext(Utils.class.getName(), new UsernamePasswordHandler(user, pass));
      lc.login();

      // 2. Perform the work as authenticated Subject.
      final String responseBody =
          Subject.doAs(
              lc.getSubject(),
              new PrivilegedExceptionAction<String>() {
                public String run() throws Exception {
                  final HttpResponse response = httpClient.execute(httpGet);
                  int statusCode = response.getStatusLine().getStatusCode();
                  assertEquals(
                      "Unexpected status code returned after the authentication.",
                      expectedStatusCode,
                      statusCode);
                  return EntityUtils.toString(response.getEntity());
                }
              });
      lc.logout();
      return responseBody;
    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpClient.getConnectionManager().shutdown();
    }
  }