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

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

Introduction

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

Prototype

Principal getUserPrincipal();

Source Link

Usage

From source file:org.apache.cloudstack.cloudian.client.CloudianClient.java

private void checkAuthFailure(final HttpResponse response) {
    if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        final Credentials credentials = httpContext.getCredentialsProvider().getCredentials(AuthScope.ANY);
        LOG.error(/* w  w w .j a  v  a2  s  . co  m*/
                "Cloudian admin API authentication failed, please check Cloudian configuration. Admin auth principal="
                        + credentials.getUserPrincipal() + ", password=" + credentials.getPassword()
                        + ", API url=" + adminApiUrl);
        throw new ServerApiException(ApiErrorCode.UNAUTHORIZED,
                "Cloudian backend API call unauthorized, please ask your administrator to fix integration issues.");
    }
}

From source file:net.java.sip.communicator.service.httputil.HttpUtils.java

/**
 * Posting form to <tt>address</tt>. For submission we use POST method
 * which is "application/x-www-form-urlencoded" encoded.
 * @param httpClient the http client//from  ww w.j  a  v a 2 s  .com
 * @param postMethod the post method
 * @param address HTTP address.
 * @param formParamNames the parameter names to include in post.
 * @param formParamValues the corresponding parameter values to use.
 * @param usernameParamIx the index of the username parameter in the
 * <tt>formParamNames</tt> and <tt>formParamValues</tt>
 * if any, otherwise -1.
 * @param passwordParamIx the index of the password parameter in the
 * <tt>formParamNames</tt> and <tt>formParamValues</tt>
 * if any, otherwise -1.
 * @param headerParamNames additional header name to include
 * @param headerParamValues corresponding header value to include
 * @return the result or null if send was not possible or
 * credentials ask if any was canceled.
 */
private static HttpEntity postForm(DefaultHttpClient httpClient, HttpPost postMethod, String address,
        ArrayList<String> formParamNames, ArrayList<String> formParamValues, int usernameParamIx,
        int passwordParamIx, RedirectHandler redirectHandler, List<String> headerParamNames,
        List<String> headerParamValues) throws Throwable {
    // if we have username and password in the parameters, lets
    // retrieve their values
    // if there are already filled skip asking the user
    Credentials creds = null;
    if (usernameParamIx != -1 && usernameParamIx < formParamNames.size() && passwordParamIx != -1
            && passwordParamIx < formParamNames.size()
            && (formParamValues.get(usernameParamIx) == null
                    || formParamValues.get(usernameParamIx).length() == 0)
            && (formParamValues.get(passwordParamIx) == null
                    || formParamValues.get(passwordParamIx).length() == 0)) {
        URL url = new URL(address);
        HTTPCredentialsProvider prov = (HTTPCredentialsProvider) httpClient.getCredentialsProvider();

        // don't allow empty username
        while (creds == null || creds.getUserPrincipal() == null
                || StringUtils.isNullOrEmpty(creds.getUserPrincipal().getName())) {
            creds = prov.getCredentials(new AuthScope(url.getHost(), url.getPort()));

            // it was user canceled lets stop processing
            if (creds == null && !prov.retry()) {
                return null;
            }
        }
    }

    // construct the name value pairs we will be sending
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    // there can be no params
    if (formParamNames != null) {
        for (int i = 0; i < formParamNames.size(); i++) {
            // we are on the username index, insert retrieved username value
            if (i == usernameParamIx && creds != null) {
                parameters
                        .add(new BasicNameValuePair(formParamNames.get(i), creds.getUserPrincipal().getName()));
            } // we are on the password index, insert retrieved password val
            else if (i == passwordParamIx && creds != null) {
                parameters.add(new BasicNameValuePair(formParamNames.get(i), creds.getPassword()));
            } else // common name value pair, all info is present
            {
                parameters.add(new BasicNameValuePair(formParamNames.get(i), formParamValues.get(i)));
            }
        }
    }

    // our custom strategy, will check redirect handler should we redirect
    // if missing will use the default handler
    httpClient.setRedirectStrategy(new CustomRedirectStrategy(redirectHandler, parameters));

    // Uses String UTF-8 to keep compatible with android version and
    // older versions of the http client libs, as the one used
    // in debian (4.1.x)
    String s = URLEncodedUtils.format(parameters, "UTF-8");
    StringEntity entity = new StringEntity(s, "UTF-8");
    // set content type to "application/x-www-form-urlencoded"
    entity.setContentType(URLEncodedUtils.CONTENT_TYPE);

    // insert post values encoded.
    postMethod.setEntity(entity);

    if (headerParamNames != null) {
        for (int i = 0; i < headerParamNames.size(); i++) {
            postMethod.addHeader(headerParamNames.get(i), headerParamValues.get(i));
        }
    }

    // execute post
    return executeMethod(httpClient, postMethod, redirectHandler, parameters);
}

From source file:org.janusgraph.diskstorage.es.rest.RestClientSetupTest.java

@Test
public void testHttpBasicAuthConfiguration() throws Exception {

    // testing that the appropriate values are passed to the client builder via credentials provider
    final String testRealm = "testRealm";
    final String testUser = "testUser";
    final String testPassword = "testPassword";

    final CredentialsProvider cp = basicAuthTestBase(ImmutableMap.<String, String>builder().build(), testRealm,
            testUser, testPassword);// w w  w  . j  a  va2s .c o  m

    final Credentials credentials = cp
            .getCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, testRealm));
    assertNotNull(credentials);
    assertEquals(testUser, credentials.getUserPrincipal().getName());
    assertEquals(testPassword, credentials.getPassword());
}

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

/**
 * Small wrapper around HttpClient.execute() in order to wrap the IOException into a SardineException.
 *//*from w w w.j  a v  a 2  s .com*/
private HttpResponse executeWrapper(HttpRequestBase base) throws SardineException {
    try {
        if (this.authEnabled) {
            Credentials creds = this.client.getCredentialsProvider().getCredentials(AuthScope.ANY);
            String value = "Basic " + new String(Base64.encodeBase64(
                    new String(creds.getUserPrincipal().getName() + ":" + creds.getPassword()).getBytes()));
            base.setHeader("Authorization", value);
        }

        return this.client.execute(base);
    } catch (IOException ex) {
        base.abort();
        throw new SardineException(ex);
    }
}

From source file:org.fcrepo.apix.registry.HttpClientFactory.java

/**
 * Construct a new HttpClient.//from w ww. jav  a2  s . co m
 *
 * @return HttpClient impl.
 */
public CloseableHttpClient getClient() {
    final RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout)
            .setSocketTimeout(socketTimeout).build();

    final CredentialsProvider provider = new BasicCredentialsProvider();

    for (final AuthSpec authSpec : getAuthSpecs()) {
        LOG.debug("Using basic auth to {}://{}:{} with client", authSpec.scheme, authSpec.host, authSpec.port);
        final HttpHost host = new HttpHost(authSpec.host, authSpec.port, authSpec.scheme);

        provider.setCredentials(new AuthScope(host, AuthScope.ANY_REALM, authSpec.scheme),
                new UsernamePasswordCredentials(authSpec.username(), authSpec.passwd()));
    }

    return HttpClientBuilder.create().setDefaultRequestConfig(config)
            .addInterceptorLast(new HttpRequestInterceptor() {

                @Override
                public void process(final HttpRequest req, final HttpContext cxt)
                        throws HttpException, IOException {
                    if (!req.containsHeader(HttpHeaders.AUTHORIZATION)) {
                        final String[] hostInfo = req.getFirstHeader(HttpHeaders.HOST).getValue().split(":");
                        final Credentials creds = provider.getCredentials(new AuthScope(
                                new HttpHost(hostInfo[0],
                                        hostInfo.length > 1 ? Integer.valueOf(hostInfo[1]) : 80),
                                AuthScope.ANY_REALM, "http"));

                        if (creds != null) {
                            req.addHeader(HttpHeaders.AUTHORIZATION,
                                    "Basic " + Base64.getEncoder().encodeToString(
                                            String.format("%s:%s", creds.getUserPrincipal().getName(),
                                                    creds.getPassword()).getBytes()));
                            LOG.debug("Added auth header");
                        }
                    }
                }
            }).setDefaultCredentialsProvider(provider).build();
}

From source file:org.sahli.asciidoc.confluence.publisher.client.http.ConfluenceRestClientTest.java

@Test
public void sendRequest_withProvidedUsernameAndPassword_setsCredentialsProvider() throws Exception {
    // arrange/*from   w  w w. j av a2  s.co  m*/
    CloseableHttpClient closeableHttpClient = anyCloseableHttpClient();
    ConfluenceRestClient confluenceRestClient = new ConfluenceRestClient("http://confluence.com",
            closeableHttpClient, "username", "password");
    HttpGet httpRequest = new HttpGet("http://confluence.com");
    ArgumentCaptor<HttpContext> httpContentArgumentCaptor = ArgumentCaptor.forClass(HttpContext.class);

    // act
    confluenceRestClient.sendRequest(httpRequest);

    // assert
    verify(closeableHttpClient, times(1)).execute(eq(httpRequest), httpContentArgumentCaptor.capture());
    HttpContext httpContext = httpContentArgumentCaptor.getValue();
    HttpClientContext httpClientContext = (HttpClientContext) httpContext;
    HttpHost httpHost = HttpHost.create("http://confluence.com");
    assertThat(httpClientContext.getAuthCache().get(httpHost), not(nullValue()));

    Credentials credentials = httpClientContext.getCredentialsProvider()
            .getCredentials(new AuthScope(httpHost));
    assertThat(credentials.getPassword(), is("password"));
    assertThat(credentials.getUserPrincipal().getName(), is("username"));
}

From source file:edu.mit.mobile.android.locast.net.NetworkClient.java

public String getUsername() {
    String username = null;//from   w w w .j  a  v a  2s  .com
    final Credentials credentials = getCredentialsProvider().getCredentials(mAuthScope);
    if (credentials != null) {
        username = credentials.getUserPrincipal().getName();
    }
    return username;
}

From source file:org.odk.collect.android.utilities.EnhancedDigestScheme.java

/**
 * Creates digest-response header as defined in RFC2617.
 * //from  w  w w. ja  v a  2 s .  c  om
 * @param credentials
 *            User credentials
 * 
 * @return The digest-response as String.
 */
private Header createDigestHeader(final Credentials credentials) throws AuthenticationException {
    String uri = getParameter("uri");
    String realm = getParameter("realm");
    String nonce = getParameter("nonce");
    String opaque = getParameter("opaque");
    String method = getParameter("methodname");
    String algorithm = getParameter("algorithm");
    if (uri == null) {
        throw new IllegalStateException("URI may not be null");
    }
    if (realm == null) {
        throw new IllegalStateException("Realm may not be null");
    }
    if (nonce == null) {
        throw new IllegalStateException("Nonce may not be null");
    }

    // TODO: add support for QOP_INT
    int qop = QOP_UNKNOWN;
    String qoplist = getParameter("qop");
    if (qoplist != null) {
        StringTokenizer tok = new StringTokenizer(qoplist, ",");
        while (tok.hasMoreTokens()) {
            String variant = tok.nextToken().trim();
            if (variant.equals("auth")) {
                qop = QOP_AUTH;
                break;
            }
        }
    } else {
        qop = QOP_MISSING;
    }

    if (qop == QOP_UNKNOWN) {
        throw new AuthenticationException("None of the qop methods is supported: " + qoplist);
    }

    // If an algorithm is not specified, default to MD5.
    if (algorithm == null) {
        algorithm = "MD5";
    }
    // If an charset is not specified, default to ISO-8859-1.
    String charset = getParameter("charset");
    if (charset == null) {
        charset = "ISO-8859-1";
    }

    String digAlg = algorithm;
    if (digAlg.equalsIgnoreCase("MD5-sess")) {
        digAlg = "MD5";
    }

    MessageDigest digester;
    try {
        digester = createMessageDigest(digAlg);
    } catch (UnsupportedDigestAlgorithmException ex) {
        throw new AuthenticationException("Unsuppported digest algorithm: " + digAlg);
    }

    String uname = credentials.getUserPrincipal().getName();
    String pwd = credentials.getPassword();

    if (nonce.equals(this.lastNonce)) {
        nounceCount++;
    } else {
        nounceCount = 1;
        cnonce = null;
        lastNonce = nonce;
    }
    StringBuilder sb = new StringBuilder(256);
    Formatter formatter = new Formatter(sb, Locale.US);
    formatter.format("%08x", nounceCount);
    String nc = sb.toString();

    if (cnonce == null) {
        cnonce = createCnonce();
    }

    a1 = null;
    a2 = null;
    // 3.2.2.2: Calculating digest
    if (algorithm.equalsIgnoreCase("MD5-sess")) {
        // H( unq(username-value) ":" unq(realm-value) ":" passwd )
        // ":" unq(nonce-value)
        // ":" unq(cnonce-value)

        // calculated one per session
        sb.setLength(0);
        sb.append(uname).append(':').append(realm).append(':').append(pwd);
        String checksum = encode(digester.digest(EncodingUtils.getBytes(sb.toString(), charset)));
        sb.setLength(0);
        sb.append(checksum).append(':').append(nonce).append(':').append(cnonce);
        a1 = sb.toString();
    } else {
        // unq(username-value) ":" unq(realm-value) ":" passwd
        sb.setLength(0);
        sb.append(uname).append(':').append(realm).append(':').append(pwd);
        a1 = sb.toString();
    }

    String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset)));

    if (qop == QOP_AUTH) {
        // Method ":" digest-uri-value
        a2 = method + ':' + uri;
    } else if (qop == QOP_AUTH_INT) {
        // Method ":" digest-uri-value ":" H(entity-body)
        // TODO: calculate entity hash if entity is repeatable
        throw new AuthenticationException("qop-int method is not suppported");
    } else {
        a2 = method + ':' + uri;
    }

    String hasha2 = encode(digester.digest(EncodingUtils.getBytes(a2, charset)));

    // 3.2.2.1

    String digestValue;
    if (qop == QOP_MISSING) {
        sb.setLength(0);
        sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2);
        digestValue = sb.toString();
    } else {
        sb.setLength(0);
        sb.append(hasha1).append(':').append(nonce).append(':').append(nc).append(':').append(cnonce)
                .append(':').append(qop == QOP_AUTH_INT ? "auth-int" : "auth").append(':').append(hasha2);
        digestValue = sb.toString();
    }

    String digest = encode(digester.digest(EncodingUtils.getAsciiBytes(digestValue)));

    CharArrayBuffer buffer = new CharArrayBuffer(128);
    if (isProxy()) {
        buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
        buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": Digest ");

    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(20);
    params.add(new BasicNameValuePair("username", uname));
    params.add(new BasicNameValuePair("realm", realm));
    params.add(new BasicNameValuePair("nonce", nonce));
    params.add(new BasicNameValuePair("uri", uri));
    params.add(new BasicNameValuePair("response", digest));

    if (qop != QOP_MISSING) {
        params.add(new BasicNameValuePair("qop", qop == QOP_AUTH_INT ? "auth-int" : "auth"));
        params.add(new BasicNameValuePair("nc", nc));
        params.add(new BasicNameValuePair("cnonce", cnonce));
    }
    if (algorithm != null) {
        params.add(new BasicNameValuePair("algorithm", algorithm));
    }
    if (opaque != null) {
        params.add(new BasicNameValuePair("opaque", opaque));
    }

    for (int i = 0; i < params.size(); i++) {
        BasicNameValuePair param = params.get(i);
        if (i > 0) {
            buffer.append(", ");
        }
        boolean noQuotes = "nc".equals(param.getName()) || "qop".equals(param.getName());
        BasicHeaderValueFormatter.DEFAULT.formatNameValuePair(buffer, param, !noQuotes);
    }
    return new BufferedHeader(buffer);
}

From source file:org.apache.http.contrib.auth.AWSScheme.java

public Header authenticate(final Credentials credentials, final HttpRequest request)
        throws AuthenticationException {
    // If the Date header has not been provided add it as it is required
    if (request.getFirstHeader("Date") == null) {
        Header dateHeader = new BasicHeader("Date", DateUtils.formatDate(new Date()));
        request.addHeader(dateHeader);/*from w  ww.j  a va2s  .c o m*/
    }

    String canonicalizedAmzHeaders = getCanonicalizedAmzHeaders(request.getAllHeaders());
    String canonicalizedResource = getCanonicalizedResource(request.getRequestLine().getUri(),
            (request.getFirstHeader("Host") != null ? request.getFirstHeader("Host").getValue() : null));
    String contentMD5 = request.getFirstHeader("Content-MD5") != null
            ? request.getFirstHeader("Content-MD5").getValue()
            : "";
    String contentType = request.getFirstHeader("Content-Type") != null
            ? request.getFirstHeader("Content-Type").getValue()
            : "";
    String date = request.getFirstHeader("Date").getValue();
    String method = request.getRequestLine().getMethod();

    StringBuilder toSign = new StringBuilder();
    toSign.append(method).append("\n");
    toSign.append(contentMD5).append("\n");
    toSign.append(contentType).append("\n");
    toSign.append(date).append("\n");
    toSign.append(canonicalizedAmzHeaders);
    toSign.append(canonicalizedResource);

    String signature = calculateRFC2104HMAC(toSign.toString(), credentials.getPassword());

    String headerValue = NAME + " " + credentials.getUserPrincipal().getName() + ":" + signature.trim();

    return new BasicHeader("Authorization", headerValue);
}