org.apache.http.auth.Credentials

Here are the examples of the java api class org.apache.http.auth.Credentials taken from open source projects.

1. AuthHelperTest#getCredentials()

Project: vso-intellij
File: AuthHelperTest.java
@Test
public void getCredentials() {
    // Basic TFS
    final AuthenticationInfo info = new AuthenticationInfo("name1", "pass1", "server1", "display1");
    final Credentials credentials = AuthHelper.getCredentials(ServerContext.Type.TFS, info);
    Assert.assertTrue(credentials instanceof NTCredentials);
    Assert.assertEquals("name1", credentials.getUserPrincipal().getName());
    Assert.assertEquals("pass1", credentials.getPassword());
    // Basic VSO
    final AuthenticationInfo info2 = new AuthenticationInfo("name2", "pass2", "server2", "display2");
    final Credentials credentials2 = AuthHelper.getCredentials(ServerContext.Type.VSO, info2);
    Assert.assertTrue(credentials2 instanceof UsernamePasswordCredentials);
    Assert.assertEquals("name2", credentials2.getUserPrincipal().getName());
    Assert.assertEquals("pass2", credentials2.getPassword());
    // domain parsing
    createAndVerifyNTCredentials("domain", "name", "domain/name", "pass");
    createAndVerifyNTCredentials("domain", "name", "domain\\name", "pass");
    createAndVerifyNTCredentials("domain", "name", "name@domain", "pass");
}

2. HttpSecurityIT#testAuroraAdmin()

Project: aurora
File: HttpSecurityIT.java
@Test
public void testAuroraAdmin() throws TException, ServletException, IOException {
    expect(auroraAdmin.snapshot()).andReturn(OK);
    expect(auroraAdmin.listBackups()).andReturn(OK);
    expectShiroAfterAuthFilter().times(12);
    replayAndStart();
    assertEquals(OK, getAuthenticatedClient(ROOT).snapshot());
    for (Credentials credentials : INVALID_CREDENTIALS) {
        assertSnapshotFails(getAuthenticatedClient(credentials));
    }
    for (Credentials credentials : Sets.difference(VALID_CREDENTIALS, ImmutableSet.of(ROOT))) {
        assertEquals(ResponseCode.AUTH_FAILED, getAuthenticatedClient(credentials).snapshot().getResponseCode());
    }
    assertEquals(OK, getAuthenticatedClient(BACKUP_SERVICE).listBackups());
}

3. HttpClientConfigTest#defaultCredentials()

Project: Jest
File: HttpClientConfigTest.java
@Test
public void defaultCredentials() {
    String user = "ceo";
    String password = "12345";
    HttpClientConfig httpClientConfig = new HttpClientConfig.Builder("localhost").defaultCredentials(user, password).build();
    CredentialsProvider credentialsProvider = httpClientConfig.getCredentialsProvider();
    Credentials credentials = credentialsProvider.getCredentials(new AuthScope("localhost", 80));
    assertEquals(user, credentials.getUserPrincipal().getName());
    assertEquals(password, credentials.getPassword());
}

4. WebServiceClient#getResponse()

Project: GeoIP2-java
File: WebServiceClient.java
private HttpGet getResponse(URL url) throws GeoIp2Exception, IOException {
    Credentials credentials = new UsernamePasswordCredentials(Integer.toString(userId), licenseKey);
    HttpGet request;
    try {
        request = new HttpGet(url.toURI());
    } catch (URISyntaxException e) {
        throw new GeoIp2Exception("Error parsing request URL", e);
    }
    try {
        request.addHeader(new BasicScheme().authenticate(credentials, request, null));
    } catch (org.apache.http.auth.AuthenticationException e) {
        throw new AuthenticationException("Error setting up request authentication", e);
    }
    request.addHeader("Accept", "application/json");
    return request;
}

5. JaxrsClientProvider#getClientConfig()

Project: vsts-authentication-library-for-java
File: JaxrsClientProvider.java
private ClientConfig getClientConfig(final String username, final String password) {
    Debug.Assert(username != null, "username cannot be null");
    Debug.Assert(password != null, "password cannot be null");
    final Credentials credentials = new UsernamePasswordCredentials(username, password);
    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);
    addProxySettings(clientConfig);
    return clientConfig;
}

6. CredentialItem#setUpCredentials()

Project: opensearchserver
File: CredentialItem.java
public void setUpCredentials(CredentialsProvider credentialProvider, HttpRequestBase httpBaseRequest) {
    if (StringUtils.isEmpty(username))
        return;
    Credentials credentials = null;
    switch(type) {
        case BASIC_DIGEST:
            credentials = new UsernamePasswordCredentials(getUsername(), getPassword());
            break;
        case NTLM:
            credentials = new NTCredentials(getUsername(), getPassword(), getWorkstation(), getDomain());
            break;
        case HTTP_HEADER:
            httpBaseRequest.addHeader(username, password);
            break;
    }
    if (credentials != null)
        credentialProvider.setCredentials(AuthScope.ANY, credentials);
}

7. BasicCredentials#authenticate()

Project: jira-client
File: BasicCredentials.java
/**
     * Sets the Authorization header for the given request.
     *
     * @param req HTTP request to authenticate
     */
public void authenticate(HttpRequest req) {
    Credentials creds = new UsernamePasswordCredentials(username, password);
    req.addHeader(BasicScheme.authenticate(creds, "utf-8", false));
}

8. RESTActivityCredentialsProvider#getCredentials()

Project: incubator-taverna-common-activities
File: RESTActivityCredentialsProvider.java
@Override
public Credentials getCredentials(AuthScope authscope) {
    logger.info("Looking for credentials for: Host - " + authscope.getHost() + ";" + "Port - " + authscope.getPort() + ";" + "Realm - " + authscope.getRealm() + ";" + "Authentication scheme - " + authscope.getScheme());
    // Ask the superclass first
    Credentials creds = super.getCredentials(authscope);
    if (creds != null) {
        /*
			 * We have used setCredentials() on this class (for proxy host,
			 * port, username,password) just before we invoked the http request,
			 * which will then pick the proxy credentials up from here.
			 */
        return creds;
    }
    // Otherwise, ask Credential Manager if is can provide the credential
    String AUTHENTICATION_REQUEST_MSG = "This REST service requires authentication in " + authscope.getRealm();
    try {
        UsernamePassword credentials = null;
        /*
			 * if port is 80 - use HTTP, don't append port if port is 443 - use
			 * HTTPS, don't append port any other port - append port + do 2
			 * tests:
			 * 
			 * --- test HTTPS first has...()
			 * --- if not there, do get...() for HTTP (which will save the thing)
			 *
			 * (save both these entries for HTTP + HTTPS if not there)
			 */
        // build the service URI back to front
        StringBuilder serviceURI = new StringBuilder();
        serviceURI.insert(0, "/#" + URLEncoder.encode(authscope.getRealm(), "UTF-16"));
        if (authscope.getPort() != DEFAULT_HTTP_PORT && authscope.getPort() != DEFAULT_HTTPS_PORT) {
            // non-default port - add port name to the URI
            serviceURI.insert(0, ":" + authscope.getPort());
        }
        serviceURI.insert(0, authscope.getHost());
        serviceURI.insert(0, "://");
        // now the URI is complete, apart from the protocol name
        if (authscope.getPort() == DEFAULT_HTTP_PORT || authscope.getPort() == DEFAULT_HTTPS_PORT) {
            // definitely HTTP or HTTPS
            serviceURI.insert(0, (authscope.getPort() == DEFAULT_HTTP_PORT ? HTTP_PROTOCOL : HTTPS_PROTOCOL));
            // request credentials from CrendentialManager
            credentials = credentialManager.getUsernameAndPasswordForService(URI.create(serviceURI.toString()), true, AUTHENTICATION_REQUEST_MSG);
        } else {
            /*
				 * non-default port - will need to try both HTTP and HTTPS; just
				 * check (no pop-up will be shown) if credentials are there -
				 * one protocol that matched will be used; if
				 */
            if (credentialManager.hasUsernamePasswordForService(URI.create(HTTPS_PROTOCOL + serviceURI.toString()))) {
                credentials = credentialManager.getUsernameAndPasswordForService(URI.create(HTTPS_PROTOCOL + serviceURI.toString()), true, AUTHENTICATION_REQUEST_MSG);
            } else if (credentialManager.hasUsernamePasswordForService(URI.create(HTTP_PROTOCOL + serviceURI.toString()))) {
                credentials = credentialManager.getUsernameAndPasswordForService(URI.create(HTTP_PROTOCOL + serviceURI.toString()), true, AUTHENTICATION_REQUEST_MSG);
            } else {
                /*
					 * Neither of the two options succeeded, request details with a
					 * popup for HTTP...
					 */
                credentials = credentialManager.getUsernameAndPasswordForService(URI.create(HTTP_PROTOCOL + serviceURI.toString()), true, AUTHENTICATION_REQUEST_MSG);
                /*
					 * ...then save a second entry with HTTPS protocol (if the
					 * user has chosen to save the credentials)
					 */
                if (credentials != null && credentials.isShouldSave()) {
                    credentialManager.addUsernameAndPasswordForService(credentials, URI.create(HTTPS_PROTOCOL + serviceURI.toString()));
                }
            }
        }
        if (credentials != null) {
            logger.info("Credentials obtained successfully");
            return new RESTActivityCredentials(credentials.getUsername(), credentials.getPasswordAsString());
        }
    } catch (Exception e) {
        logger.error("Unexpected error while trying to obtain user's credential from CredentialManager", e);
    }
    // error or nothing was found
    logger.info("Credentials not found - the user must have refused to enter them.");
    return null;
}

9. DefaultAsyncRequestDirector#updateAuthState()

Project: httpasyncclient
File: DefaultAsyncRequestDirector.java
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 = this.connmgr.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);
}

10. BasicAuthenticationHttpClientConfigurer#configureHttpClient()

Project: camel
File: BasicAuthenticationHttpClientConfigurer.java
public void configureHttpClient(HttpClientBuilder clientBuilder) {
    Credentials defaultcreds;
    if (domain != null) {
        defaultcreds = new NTCredentials(username, password, host, domain);
    } else {
        defaultcreds = new UsernamePasswordCredentials(username, password);
    }
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, defaultcreds);
    clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}

11. HTTPProxyConfigurator#configure()

Project: axis2-java
File: HTTPProxyConfigurator.java
/**
     * Configure HTTP Proxy settings of commons-httpclient HostConfiguration.
     * Proxy settings can be get from axis2.xml, Java proxy settings or can be
     * override through property in message context.
     * <p/>
     * HTTP Proxy setting element format: <parameter name="Proxy">
     * <Configuration> <ProxyHost>example.org</ProxyHost>
     * <ProxyPort>3128</ProxyPort> <ProxyUser>EXAMPLE/John</ProxyUser>
     * <ProxyPassword>password</ProxyPassword> <Configuration> <parameter>
     *
     * @param messageContext
     *            in message context for
     * @param httpClient
     *            instance
     * @throws org.apache.axis2.AxisFault
     *             if Proxy settings are invalid
     */
public static void configure(MessageContext messageContext, AbstractHttpClient httpClient) throws AxisFault {
    Credentials proxyCredentials = null;
    String proxyHost = null;
    String nonProxyHosts = null;
    Integer proxyPort = -1;
    String proxyUser = null;
    String proxyPassword = null;
    // Getting configuration values from Axis2.xml
    Parameter proxySettingsFromAxisConfig = messageContext.getConfigurationContext().getAxisConfiguration().getParameter(HTTPTransportConstants.ATTR_PROXY);
    if (proxySettingsFromAxisConfig != null) {
        OMElement proxyConfiguration = getProxyConfigurationElement(proxySettingsFromAxisConfig);
        proxyHost = getProxyHost(proxyConfiguration);
        proxyPort = getProxyPort(proxyConfiguration);
        proxyUser = getProxyUser(proxyConfiguration);
        proxyPassword = getProxyPassword(proxyConfiguration);
        if (proxyUser != null) {
            if (proxyPassword == null) {
                proxyPassword = "";
            }
            proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
            int proxyUserDomainIndex = proxyUser.indexOf("\\");
            if (proxyUserDomainIndex > 0) {
                String domain = proxyUser.substring(0, proxyUserDomainIndex);
                if (proxyUser.length() > proxyUserDomainIndex + 1) {
                    String user = proxyUser.substring(proxyUserDomainIndex + 1);
                    proxyCredentials = new NTCredentials(user, proxyPassword, proxyHost, domain);
                }
            }
        }
    }
    // If there is runtime proxy settings, these settings will override
    // settings from axis2.xml
    HttpTransportProperties.ProxyProperties proxyProperties = (HttpTransportProperties.ProxyProperties) messageContext.getProperty(HTTPConstants.PROXY);
    if (proxyProperties != null) {
        String proxyHostProp = proxyProperties.getProxyHostName();
        if (proxyHostProp == null || proxyHostProp.length() <= 0) {
            throw new AxisFault("HTTP Proxy host is not available. Host is a MUST parameter");
        } else {
            proxyHost = proxyHostProp;
        }
        proxyPort = proxyProperties.getProxyPort();
        // Overriding credentials
        String userName = proxyProperties.getUserName();
        String password = proxyProperties.getPassWord();
        String domain = proxyProperties.getDomain();
        if (userName != null && password != null && domain != null) {
            proxyCredentials = new NTCredentials(userName, password, proxyHost, domain);
        } else if (userName != null && domain == null) {
            proxyCredentials = new UsernamePasswordCredentials(userName, password);
        }
    }
    // Overriding proxy settings if proxy is available from JVM settings
    String host = System.getProperty(HTTPTransportConstants.HTTP_PROXY_HOST);
    if (host != null) {
        proxyHost = host;
    }
    String port = System.getProperty(HTTPTransportConstants.HTTP_PROXY_PORT);
    if (port != null) {
        proxyPort = Integer.parseInt(port);
    }
    if (proxyCredentials != null) {
        // TODO : Set preemptive authentication, but its not recommended in HC 4
        httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, proxyCredentials);
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
}

12. LibRequestDirector#updateAuthState()

Project: YiBo
File: LibRequestDirector.java
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 (DEBUG) {
        Logger.debug("Authentication scope: {}", authScope);
    }
    Credentials creds = authState.getCredentials();
    if (creds == null) {
        creds = credsProvider.getCredentials(authScope);
        if (DEBUG) {
            if (creds != null) {
                Logger.debug("Found credentials");
            } else {
                Logger.debug("Credentials not found");
            }
        }
    } else {
        if (authScheme.isComplete()) {
            if (DEBUG) {
                Logger.debug("Authentication failed");
            }
            creds = null;
        }
    }
    authState.setAuthScope(authScope);
    authState.setCredentials(creds);
}

13. ServerContextTest#getClientConfig()

Project: vso-intellij
File: ServerContextTest.java
@Test
public void getClientConfig() {
    AuthenticationInfo info = new AuthenticationInfo("user1", "pass", "server1", "4display");
    final ClientConfig config = ServerContext.getClientConfig(ServerContext.Type.TFS, info, false);
    final Map<String, Object> properties = config.getProperties();
    Assert.assertEquals(3, properties.size());
    Assert.assertEquals(true, properties.get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION));
    Assert.assertEquals(RequestEntityProcessing.BUFFERED, properties.get(ClientProperties.REQUEST_ENTITY_PROCESSING));
    final CredentialsProvider cp = (CredentialsProvider) properties.get(ApacheClientProperties.CREDENTIALS_PROVIDER);
    final Credentials credentials = cp.getCredentials(AuthScope.ANY);
    Assert.assertEquals(info.getPassword(), credentials.getPassword());
    Assert.assertEquals(info.getUserName(), credentials.getUserPrincipal().getName());
    // Make sure Fiddler properties get set if property is on
    final ClientConfig config2 = ServerContext.getClientConfig(ServerContext.Type.TFS, info, true);
    final Map<String, Object> properties2 = config2.getProperties();
    //proxy setting doesn't automatically mean we need to setup ssl trust store anymore
    Assert.assertEquals(4, properties2.size());
    Assert.assertNotNull(properties2.get(ClientProperties.PROXY_URI));
    Assert.assertNull(properties2.get(ApacheClientProperties.SSL_CONFIG));
    info = new AuthenticationInfo("users1", "pass", "https://tfsonprem.test", "4display");
    final ClientConfig config3 = ServerContext.getClientConfig(ServerContext.Type.TFS, info, false);
    final Map<String, Object> properties3 = config3.getProperties();
    Assert.assertEquals(4, properties3.size());
    Assert.assertNull(properties3.get(ClientProperties.PROXY_URI));
    Assert.assertNotNull(properties3.get(ApacheClientProperties.SSL_CONFIG));
}

14. AuthHelperTest#createAuthInfo()

Project: vso-intellij
File: AuthHelperTest.java
@Test
public void createAuthInfo() {
    final Credentials credentials = new UsernamePasswordCredentials("userName", "password");
    final AuthenticationInfo info = AuthHelper.createAuthenticationInfo("server", credentials);
    Assert.assertEquals("userName", info.getUserName());
    Assert.assertEquals("password", info.getPassword());
    Assert.assertEquals("server", info.getServerUri());
    Assert.assertEquals("userName", info.getUserNameForDisplay());
}

15. AuthHelperTest#createAndVerifyNTCredentials()

Project: vso-intellij
File: AuthHelperTest.java
private void createAndVerifyNTCredentials(final String domain, final String name, final String domainName, final String pass) {
    final AuthenticationInfo info = new AuthenticationInfo(domainName, pass, "server", "display");
    final Credentials credentials = AuthHelper.getCredentials(ServerContext.Type.TFS, info);
    Assert.assertTrue(credentials instanceof NTCredentials);
    Assert.assertEquals(name, ((NTCredentials) credentials).getUserName());
    Assert.assertEquals(domain, ((NTCredentials) credentials).getDomain().toLowerCase());
    if (SystemHelper.getComputerName() != null) {
        //coming back null when running from command line on Mac, works inside IDE
        Assert.assertEquals(SystemHelper.getComputerName().toLowerCase(), ((NTCredentials) credentials).getWorkstation().toLowerCase());
    }
    Assert.assertEquals(pass, credentials.getPassword());
}

16. ServerContext#getClientConfig()

Project: vso-intellij
File: ServerContext.java
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 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);
    }
    // if this is a onPrem server and the uri starts with https, we need to setup ssl
    if (isSSLEnabledOnPrem(type, authenticationInfo.getServerUri())) {
        clientConfig.property(ApacheClientProperties.SSL_CONFIG, getSslConfigurator());
    }
    return clientConfig;
}

17. SlackNotificationMainSettingsTest#TestFullConfig()

Project: tcSlackBuildNotifier
File: SlackNotificationMainSettingsTest.java
@Test
public void TestFullConfig() {
    String expectedConfigDirectory = ".";
    ServerPaths serverPaths = mock(ServerPaths.class);
    when(serverPaths.getConfigDir()).thenReturn(expectedConfigDirectory);
    SlackNotificationMainSettings whms = new SlackNotificationMainSettings(server, serverPaths);
    whms.register();
    whms.readFrom(getFullConfigElement());
    String proxy = whms.getProxy();
    SlackNotificationProxyConfig whpc = whms.getProxyConfig();
    assertTrue(proxy.equals(this.proxyHost));
    assertTrue(whpc.getProxyHost().equals(this.proxyHost));
    assertTrue(whpc.getProxyPort().equals(this.proxyPort));
    assertTrue(whms.getDefaultChannel().equals(this.defaultChannel));
    assertTrue(whms.getTeamName().equals(this.teamName));
    assertTrue(whms.getToken().equals(this.token));
    assertTrue(whms.getIconUrl().equals(this.iconUrl));
    assertTrue(whms.getBotName().equals(this.botName));
    assertTrue(whms.getShowBuildAgent());
    assertTrue(whms.getShowElapsedBuildTime());
    assertFalse(whms.getShowCommits());
    assertEquals(15, whms.getMaxCommitsToDisplay());
    assertTrue(whms.getShowFailureReason());
    Credentials credentials = whpc.getCreds();
    assertEquals("some-username", credentials.getUserPrincipal().getName());
    assertEquals("some-password", credentials.getPassword());
}

18. PinboardApi#pinboardAuthenticate()

Project: PinDroid
File: PinboardApi.java
/**
     * Attempts to authenticate to Pinboard using a legacy Pinboard account.
     * 
     * @param username The user's username.
     * @param password The user's password.
     * @param handler The hander instance from the calling UI thread.
     * @param context The context of the calling Activity.
     * @return The boolean result indicating whether the user was
     *         successfully authenticated.
     * @throws  
     */
public static String pinboardAuthenticate(String username, String password) {
    final HttpResponse resp;
    Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(PINBOARD_AUTHORITY);
    builder.appendEncodedPath(AUTH_TOKEN_URI);
    Uri uri = builder.build();
    HttpGet request = new HttpGet(String.valueOf(uri));
    DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient();
    CredentialsProvider provider = client.getCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    provider.setCredentials(SCOPE, credentials);
    try {
        resp = client.execute(request);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            final HttpEntity entity = resp.getEntity();
            InputStream instream = entity.getContent();
            SaxTokenParser parser = new SaxTokenParser(instream);
            PinboardAuthToken token = parser.parse();
            instream.close();
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Successful authentication");
                Log.v(TAG, "AuthToken: " + token.getToken());
            }
            return token.getToken();
        } else {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Error authenticating" + resp.getStatusLine());
            }
            return null;
        }
    } catch (final IOException e) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "IOException when getting authtoken", e);
        }
        return null;
    } catch (ParseException e) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "ParseException when getting authtoken", e);
        }
        return null;
    } finally {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "getAuthtoken completing");
        }
    }
}

19. NetworkUtilities#pinboardAuthenticate()

Project: PinDroid
File: NetworkUtilities.java
/**
     * Attempts to authenticate to Pinboard using a legacy Pinboard account.
     * 
     * @param username The user's username.
     * @param password The user's password.
     * @param handler The hander instance from the calling UI thread.
     * @param context The context of the calling Activity.
     * @return The boolean result indicating whether the user was
     *         successfully authenticated.
     */
public static boolean pinboardAuthenticate(String username, String password) {
    final HttpResponse resp;
    Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(PINBOARD_AUTHORITY);
    builder.appendEncodedPath("v1/posts/update");
    Uri uri = builder.build();
    HttpGet request = new HttpGet(String.valueOf(uri));
    DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient();
    CredentialsProvider provider = client.getCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    provider.setCredentials(SCOPE, credentials);
    try {
        resp = client.execute(request);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Successful authentication");
            }
            return true;
        } else {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Error authenticating" + resp.getStatusLine());
            }
            return false;
        }
    } catch (final IOException e) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "IOException when getting authtoken", e);
        }
        return false;
    } finally {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "getAuthtoken completing");
        }
    }
}

20. HadoopStatusGetter#getHttpResponseWithKerberosAuth()

Project: kylin
File: HadoopStatusGetter.java
private String getHttpResponseWithKerberosAuth(String url) throws IOException {
    String krb5ConfigPath = System.getProperty("java.security.krb5.conf");
    if (krb5ConfigPath == null) {
        krb5ConfigPath = DEFAULT_KRB5_CONFIG_LOCATION;
    }
    boolean skipPortAtKerberosDatabaseLookup = true;
    System.setProperty("java.security.krb5.conf", krb5ConfigPath);
    System.setProperty("sun.security.krb5.debug", "true");
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(skipPortAtKerberosDatabaseLookup)).build();
    CloseableHttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry).build();
    HttpClientContext context = HttpClientContext.create();
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    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);
    String response = null;
    while (response == null) {
        if (url.startsWith("https://")) {
            registerEasyHttps();
        }
        if (url.contains("anonymous=true") == false) {
            url += url.contains("?") ? "&" : "?";
            url += "anonymous=true";
        }
        HttpGet httpget = new HttpGet(url);
        httpget.addHeader("accept", "application/json");
        try {
            CloseableHttpResponse httpResponse = client.execute(httpget, context);
            String redirect = null;
            org.apache.http.Header h = httpResponse.getFirstHeader("Location");
            if (h != null) {
                redirect = h.getValue();
                if (isValidURL(redirect) == false) {
                    logger.info("Get invalid redirect url, skip it: " + redirect);
                    Thread.sleep(1000L);
                    continue;
                }
            } else {
                h = httpResponse.getFirstHeader("Refresh");
                if (h != null) {
                    String s = h.getValue();
                    int cut = s.indexOf("url=");
                    if (cut >= 0) {
                        redirect = s.substring(cut + 4);
                        if (isValidURL(redirect) == false) {
                            logger.info("Get invalid redirect url, skip it: " + redirect);
                            Thread.sleep(1000L);
                            continue;
                        }
                    }
                }
            }
            if (redirect == null) {
                response = IOUtils.toString(httpResponse.getEntity().getContent());
                logger.debug("Job " + mrJobId + " get status check result.\n");
            } else {
                url = redirect;
                logger.debug("Job " + mrJobId + " check redirect url " + url + ".\n");
            }
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        } finally {
            httpget.releaseConnection();
        }
    }
    return response;
}