Example usage for org.apache.http.auth Credentials Credentials

List of usage examples for org.apache.http.auth Credentials Credentials

Introduction

In this page you can find the example usage for org.apache.http.auth Credentials Credentials.

Prototype

Credentials

Source Link

Usage

From source file:com.mycompany.kerberosbyip.NewMain.java

private void configureHttpClient(final DefaultHttpClient httpclient) throws GeneralSecurityException {
    AuthSchemeRegistry registry = new AuthSchemeRegistry();
    registry.register(KERBEROS, new WsmanKerberosSchemeFactory(true, "WSMAN", ipAddress, port));
    registry.register(SPNEGO, new WsmanSPNegoSchemeFactory(true, "WSMAN", ipAddress, port));
    httpclient.setAuthSchemes(registry);

    final Credentials jaasCreds = new Credentials() {
        @Override//  w w  w. j  a  va 2 s  . c o m
        public String getPassword() {
            return null;
        }

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

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

From source file:com.googlecode.sardine.AuthenticationTest.java

@Test
public void testBasicPreemptiveAuth() throws Exception {
    final DefaultHttpClient client = new DefaultHttpClient();
    final CountDownLatch count = new CountDownLatch(1);
    client.setCredentialsProvider(new BasicCredentialsProvider() {
        @Override//from   ww  w  .j a  v a 2  s.c o  m
        public Credentials getCredentials(AuthScope authscope) {
            // Set flag that credentials have been used indicating preemptive authentication
            count.countDown();
            return new Credentials() {
                public Principal getUserPrincipal() {
                    return new BasicUserPrincipal("anonymous");
                }

                public String getPassword() {
                    return "invalid";
                }
            };
        }
    });
    SardineImpl sardine = new SardineImpl(client);
    URI url = URI.create("http://sudo.ch/dav/basic/");
    //Send basic authentication header in initial request
    sardine.enablePreemptiveAuthentication(url.getHost());
    try {
        sardine.list(url.toString());
        fail("Expected authorization failure");
    } catch (SardineException e) {
        // Expect Authorization Failed
        assertEquals(401, e.getStatusCode());
        // Make sure credentials have been queried
        assertEquals("No preemptive authentication attempt", 0, count.getCount());
    }
}

From source file:com.github.sardine.AuthenticationTest.java

@Test
public void testBasicPreemptiveAuth() throws Exception {
    final HttpClientBuilder client = HttpClientBuilder.create();
    final CountDownLatch count = new CountDownLatch(1);
    client.setDefaultCredentialsProvider(new BasicCredentialsProvider() {
        @Override//  w  w w . ja  va2 s .c  o  m
        public Credentials getCredentials(AuthScope authscope) {
            // Set flag that credentials have been used indicating preemptive authentication
            count.countDown();
            return new Credentials() {
                public Principal getUserPrincipal() {
                    return new BasicUserPrincipal("anonymous");
                }

                public String getPassword() {
                    return "invalid";
                }
            };
        }
    });
    SardineImpl sardine = new SardineImpl(client);
    URI url = URI.create("http://sudo.ch/dav/basic/");
    //Send basic authentication header in initial request
    sardine.enablePreemptiveAuthentication(url.getHost());
    try {
        sardine.list(url.toString());
        fail("Expected authorization failure");
    } catch (SardineException e) {
        // Expect Authorization Failed
        assertEquals(401, e.getStatusCode());
        // Make sure credentials have been queried
        assertEquals("No preemptive authentication attempt", 0, count.getCount());
    }
}

From source file:org.restheart.test.integration.SecurityAuthTokenIT.java

@Test
public void testAuthTokenResourceLocation() throws Exception {
    Response resp = adminExecutor.execute(Request.Get(rootUri));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);//  w w w .  ja v  a  2 s  .  com

    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check authorized", HttpStatus.SC_OK, statusLine.getStatusCode());

    Header[] _authToken = httpResp.getHeaders(AUTH_TOKEN_HEADER.toString());
    Header[] _authTokenValid = httpResp.getHeaders(AUTH_TOKEN_VALID_HEADER.toString());
    Header[] _authTokenLocation = httpResp.getHeaders(AUTH_TOKEN_LOCATION_HEADER.toString());

    assertNotNull("check not null auth token header", _authToken);
    assertNotNull("check not null auth token valid header", _authTokenValid);
    assertNotNull("check not null auth token location header", _authTokenLocation);

    assertTrue("check not empty array auth token header array ", _authToken.length == 1);
    assertTrue("check not empty array auth token valid header", _authTokenValid.length == 1);
    assertTrue("check not empty array auth token location header", _authTokenLocation.length == 1);

    String locationURI = _authTokenLocation[0].getValue();

    URI authTokenResourceUri = rootUri.resolve(locationURI);

    final String host = CLIENT_HOST;
    final int port = conf.getHttpPort();

    Response resp2 = unauthExecutor.authPreemptive(new HttpHost(host, port, HTTP)).auth(new Credentials() {
        @Override
        public Principal getUserPrincipal() {
            return new BasicUserPrincipal("admin");
        }

        @Override
        public String getPassword() {
            return _authToken[0].getValue();
        }
    }).execute(Request.Get(authTokenResourceUri));

    HttpResponse httpResp2 = resp2.returnResponse();
    assertNotNull(httpResp2);

    StatusLine statusLine2 = httpResp2.getStatusLine();
    assertNotNull(statusLine2);

    HttpEntity entity = httpResp2.getEntity();
    assertNotNull(entity);

    Header[] _authTokenValid2 = httpResp2.getHeaders(AUTH_TOKEN_VALID_HEADER.toString());

    assertEquals("check auth token resource URI", HttpStatus.SC_OK, statusLine2.getStatusCode());

    assertNotNull("content type not null", entity.getContentType());
    assertEquals("check content type", Representation.HAL_JSON_MEDIA_TYPE, entity.getContentType().getValue());

    String content = EntityUtils.toString(entity);

    assertNotNull("check content of auth token resource", content);

    JsonObject json = null;

    try {
        json = JsonObject.readFrom(content);
    } catch (Throwable t) {
        fail("parsing received json");
    }

    assertNotNull("check content - auth_token not null", json.get("auth_token"));
    assertNotNull("check content - auth_token_valid_until not null", json.get("auth_token_valid_until"));

    assertTrue("check content - auth_token not empty", !json.get("auth_token").asString().isEmpty());
    assertTrue("check content - auth_token_valid_until not empty",
            !json.get("auth_token_valid_until").asString().isEmpty());

    assertEquals(json.get("auth_token").asString(), _authToken[0].getValue());
    assertEquals(json.get("auth_token_valid_until").asString(), _authTokenValid2[0].getValue());
}

From source file:com.hortonworks.registries.auth.client.AuthenticatorTestCase.java

private SystemDefaultHttpClient getHttpClient() {
    final SystemDefaultHttpClient httpClient = new SystemDefaultHttpClient();
    httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory(true));
    Credentials use_jaas_creds = new Credentials() {
        public String getPassword() {
            return null;
        }// www  .  j ava2s. c  om

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

    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, use_jaas_creds);
    return httpClient;
}

From source file:org.restheart.test.integration.SecurityAuthTokenIT.java

@Test
public void testAuthTokenInvalidation() throws Exception {
    Response resp = adminExecutor.execute(Request.Get(rootUri));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);/*w ww .jav a 2  s  .c om*/

    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check authorized", HttpStatus.SC_OK, statusLine.getStatusCode());

    Header[] _authToken = httpResp.getHeaders(AUTH_TOKEN_HEADER.toString());
    Header[] _authTokenValid = httpResp.getHeaders(AUTH_TOKEN_VALID_HEADER.toString());
    Header[] _authTokenLocation = httpResp.getHeaders(AUTH_TOKEN_LOCATION_HEADER.toString());

    assertNotNull("check not null auth token header", _authToken);
    assertNotNull("check not null auth token valid header", _authTokenValid);
    assertNotNull("check not null auth token location header", _authTokenLocation);

    assertTrue("check not empty array auth token header array ", _authToken.length == 1);
    assertTrue("check not empty array auth token valid header", _authTokenValid.length == 1);
    assertTrue("check not empty array auth token location header", _authTokenLocation.length == 1);

    String locationURI = _authTokenLocation[0].getValue();

    URI authTokenResourceUri = rootUri.resolve(locationURI);

    Response resp2 = unauthExecutor.auth(new Credentials() {
        @Override
        public Principal getUserPrincipal() {
            return new BasicUserPrincipal("admin");
        }

        @Override
        public String getPassword() {
            return _authToken[0].getValue();
        }
    }).execute(Request.Delete(authTokenResourceUri));

    HttpResponse httpResp2 = resp2.returnResponse();
    assertNotNull(httpResp2);

    StatusLine statusLine2 = httpResp2.getStatusLine();
    assertNotNull(statusLine2);

    assertEquals("check auth token resource URI", HttpStatus.SC_NO_CONTENT, statusLine2.getStatusCode());

    Response resp3 = unauthExecutor.auth(new Credentials() {
        @Override
        public Principal getUserPrincipal() {
            return new BasicUserPrincipal("admin");
        }

        @Override
        public String getPassword() {
            return _authToken[0].getValue();
        }
    }).execute(Request.Get(rootUri));

    HttpResponse httpResp3 = resp3.returnResponse();
    assertNotNull(httpResp3);

    StatusLine statusLine3 = httpResp3.getStatusLine();
    assertNotNull(statusLine3);

    assertEquals("check auth token resource URI", HttpStatus.SC_UNAUTHORIZED, statusLine3.getStatusCode());
}

From source file:org.keycloak.testsuite.federation.kerberos.AbstractKerberosTest.java

protected void initHttpClient(boolean useSpnego) {
    if (client != null) {
        cleanupApacheHttpClient();/*from w  w w  .j a v  a  2  s. c  om*/
    }

    DefaultHttpClient httpClient = (DefaultHttpClient) new HttpClientBuilder().disableCookieCache(false)
            .build();

    httpClient.getAuthSchemes().register(AuthSchemes.SPNEGO, spnegoSchemeFactory);

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

            @Override
            public String getPassword() {
                return null;
            }

            @Override
            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();
}

From source file:eu.fthevenet.binjr.data.adapters.HttpDataAdapterBase.java

protected CloseableHttpClient httpClientFactory() throws CannotInitializeDataAdapterException {
    try {/* w  w  w. jav  a 2  s. c  om*/
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(createSslCustomContext(), null, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        RegistryBuilder<AuthSchemeProvider> schemeProviderBuilder = RegistryBuilder.create();
        schemeProviderBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() {
            @Override
            public Principal getUserPrincipal() {
                return null;
            }

            @Override
            public String getPassword() {
                return null;
            }
        });

        return HttpClients.custom().setDefaultAuthSchemeRegistry(schemeProviderBuilder.build())
                .setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(csf).build();
    } catch (Exception e) {
        throw new CannotInitializeDataAdapterException(
                "Could not initialize adapter to source '" + this.getSourceName() + "': " + e.getMessage(), e);
    }
}

From source file:org.apache.hadoop.gateway.SecureClusterTest.java

private CloseableHttpClient getHttpClient() {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new Credentials() {
        @Override/*from  w  w  w.  java 2 s .  c  om*/
        public Principal getUserPrincipal() {
            return new BasicUserPrincipal("guest");
        }

        @Override
        public String getPassword() {
            return "guest-password";
        }
    });

    return HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
}

From source file:com.srotya.collectd.storm.StormNimbusMetrics.java

@Override
public int config(OConfigItem config) {
    nimbusAddresses = new ArrayList<>();
    String jaasPath = "jaas.conf";
    List<OConfigItem> children = config.getChildren();
    for (OConfigItem child : children) {
        switch (child.getKey().toLowerCase()) {
        case "address":
            for (OConfigValue nimbus : child.getValues()) {
                try {
                    new URI(nimbus.toString());
                } catch (Exception e) {
                    Collectd.logError("Bad URI " + nimbus + " for Nimbus, error:" + e.getMessage());
                    return -1;
                }//  w w  w.j a v a  2 s .c om
                nimbusAddresses.add(nimbus.getString());
            }
            break;
        case "kerberos":
            kerberos = child.getValues().get(0).getBoolean();
            break;
        case "jaas":
            jaasPath = child.getValues().get(0).getString();
            break;
        }
    }
    Collectd.logInfo("Storm Nimbus Plugin: using following Nimbuses:" + nimbusAddresses);
    Collectd.logInfo("Storm Nimbus Plugin: using kerberos:" + kerberos);

    builder = HttpClientBuilder.create();
    context = HttpClientContext.create();
    if (kerberos) {
        System.setProperty("java.security.auth.login.config", jaasPath);
        System.setProperty("java.security.krb5.conf", "/etc/krb5.conf");
        System.setProperty("javax.security.auth.useSubjectCredsOnly", "true");

        login();

        Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
        builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);

        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        // This may seem odd, but specifying 'null' as principal tells java
        // to
        // use the logged in user's credentials
        Credentials useJaasCreds = new Credentials() {

            public String getPassword() {
                return null;
            }

            public Principal getUserPrincipal() {
                return null;
            }

        };
        credentialsProvider.setCredentials(new AuthScope(null, -1, null), useJaasCreds);
        context.setCredentialsProvider(credentialsProvider);

    } else {
        subject = Subject.getSubject(AccessController.getContext());
    }
    return 0;
}