Example usage for org.apache.http.impl.auth BasicScheme authenticate

List of usage examples for org.apache.http.impl.auth BasicScheme authenticate

Introduction

In this page you can find the example usage for org.apache.http.impl.auth BasicScheme authenticate.

Prototype

@Deprecated
public static Header authenticate(final Credentials credentials, final String charset, final boolean proxy) 

Source Link

Document

Returns a basic Authorization header value for the given Credentials and charset.

Usage

From source file:com.amalto.workbench.utils.HttpClientUtil.java

private static void authenticate(String username, String password, HttpUriRequest request,
        HttpContext preemptiveContext) {
    try {/*  w w w  .j  a v a  2  s .  c o m*/
        BasicScheme basicScheme = new BasicScheme();
        Header authenticateHeader = basicScheme
                .authenticate(new UsernamePasswordCredentials(username, password), request, preemptiveContext);
        request.addHeader(authenticateHeader);
    } catch (AuthenticationException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:org.siddhiesb.transport.http.conn.ProxyAuthenticator.java

public void authenticatePreemptively(final HttpRequest request, final HttpContext context)
        throws ProtocolException {
    BasicScheme basicScheme = new BasicScheme();
    basicScheme.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, "BASIC realm=\"proxy\""));
    Header authresp = basicScheme.authenticate(proxycreds, request, context);
    request.addHeader(authresp);//from   ww  w. j a v a2s.  c o m
}

From source file:org.ops4j.pax.web.itest.base.client.HttpComponentsWrapper.java

private HttpResponse getHttpResponse(String path, boolean authenticate, BasicHttpContext basicHttpContext,
        boolean async) throws IOException, KeyManagementException, UnrecoverableKeyException,
        NoSuchAlgorithmException, KeyStoreException, CertificateException, AuthenticationException,
        InterruptedException, ExecutionException {

    HttpHost targetHost = getHttpHost(path);

    BasicHttpContext localcontext = basicHttpContext == null ? new BasicHttpContext() : basicHttpContext;

    HttpGet httpget = new HttpGet(path);
    for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
        LOG.info("adding request-header: {}={}", entry.getKey(), entry.getValue());
        httpget.addHeader(entry.getKey(), entry.getValue());
    }/*  w  ww. ja  va 2  s . c  o m*/

    LOG.info("calling remote {} ...", path);
    HttpResponse response = null;
    if (!authenticate && basicHttpContext == null) {
        if (localcontext.getAttribute(ClientContext.AUTH_CACHE) != null) {
            localcontext.removeAttribute(ClientContext.AUTH_CACHE);
        }
        if (!async) {
            response = httpclient.execute(httpget, context);
        } else {
            Future<HttpResponse> future = httpAsyncClient.execute(httpget, context, null);
            response = future.get();
        }
    } else {
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth
        // cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        httpget.addHeader(basicAuth.authenticate(creds, httpget, localcontext));
        if (!async) {
            response = httpclient.execute(targetHost, httpget, localcontext);
        } else {
            Future<HttpResponse> future = httpAsyncClient.execute(targetHost, httpget, localcontext, null);
            response = future.get();
        }
    }

    LOG.info("... responded with: {}", response.getStatusLine().getStatusCode());
    return response;
}

From source file:org.apache.hadoop.gateway.hive.HiveDispatchUtils.java

public static void addCredentialsToRequest(HttpUriRequest request) {
    String principal = SubjectUtils.getCurrentEffectivePrincipalName();
    if (principal != null) {
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(principal,
                PASSWORD_PLACEHOLDER);//from w  w  w  .jav  a  2 s. c  o  m
        request.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false));
    }
}

From source file:org.ops4j.pax.web.itest.base.HttpTestClient.java

public HttpResponse getHttpResponse(String path, boolean authenticate, BasicHttpContext basicHttpContext,
        boolean async) throws IOException, KeyManagementException, UnrecoverableKeyException,
        NoSuchAlgorithmException, KeyStoreException, CertificateException, AuthenticationException,
        InterruptedException, ExecutionException {
    HttpGet httpget = null;//from  ww  w  .  ja  v  a2 s  .  co  m

    HttpHost targetHost = getHttpHost(path);

    BasicHttpContext localcontext = basicHttpContext == null ? new BasicHttpContext() : basicHttpContext;

    httpget = new HttpGet(path);
    httpget.addHeader("Accept-Language", "en");
    LOG.info("calling remote {} ...", path);
    HttpResponse response = null;
    if (!authenticate && basicHttpContext == null) {
        if (localcontext.getAttribute(ClientContext.AUTH_CACHE) != null) {
            localcontext.removeAttribute(ClientContext.AUTH_CACHE);
        }
        if (!async) {
            response = httpclient.execute(httpget, context);
        } else {
            Future<HttpResponse> future = httpAsyncClient.execute(httpget, context, null);
            response = future.get();
        }
    } else {
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        httpget.addHeader(basicAuth.authenticate(creds, httpget, localcontext));
        httpget.addHeader("Accept-Language", "en-us;q=0.8,en;q=0.5");
        if (!async) {
            response = httpclient.execute(targetHost, httpget, localcontext);
        } else {
            Future<HttpResponse> future = httpAsyncClient.execute(targetHost, httpget, localcontext, null);
            response = future.get();
        }
    }

    LOG.info("... responded with: {}", response.getStatusLine().getStatusCode());
    return response;
}

From source file:su.fmi.photoshareclient.remote.LoginHandler.java

public static boolean login(String username, char[] password) {
    try {/* w  w w. ja v  a  2s  .c  o  m*/
        ProjectProperties properties = new ProjectProperties();
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(
                "http://" + properties.get("socket") + properties.get("restEndpoint") + "/user/login");
        StringEntity input = new StringEntity(
                "{\"username\":\"" + username + "\",\"password\":\"" + new String(password) + "\"}",
                ContentType.create("application/json"));
        post.setHeader("Content-Type", "application/json");
        post.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(username, new String(password)),
                "UTF-8", false));
        post.setEntity(input);

        if (username.isEmpty() || password.length == 0) {
            return false;
        }
        HttpResponse response = (HttpResponse) client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
            String authString = username + ":" + new String(password);
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            authStringEncr = new String(authEncBytes);
            return true;
        } else {
            return false;
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
}

From source file:org.dcache.webdav.transfer.CredentialServiceClient.java

private HttpPost buildRequest(String token, String host, String clientId, String clientSecret)
        throws UnsupportedEncodingException, AuthenticationException {
    UsernamePasswordCredentials clientCreds = new UsernamePasswordCredentials(clientId, clientSecret);
    BasicScheme scheme = new BasicScheme(Charsets.UTF_8);

    HttpPost post = new HttpPost(tokenEndPoint(host));
    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("grant_type", GRANT_TYPE));
    params.add(new BasicNameValuePair("audience", clientId));
    params.add(new BasicNameValuePair("subject_token", token));
    params.add(new BasicNameValuePair("subject_token_type", TOKEN_TYPE));
    params.add(new BasicNameValuePair("scope", SCOPE));

    post.setEntity(new UrlEncodedFormEntity(params));
    post.addHeader(scheme.authenticate(clientCreds, post, new BasicHttpContext()));
    return post;/*from w  w  w. ja v a2s  .c om*/
}

From source file:com.arangodb.http.HttpManager.java

/**
 * Executes the request/*from  ww  w .j  a  v a 2s . c  o m*/
 * 
 * @param requestEntity
 *            the request
 * @return the response of the request
 * @throws ArangoException
 */
private HttpResponseEntity executeInternal(String baseUrl, HttpRequestEntity requestEntity)
        throws ArangoException, SocketException {

    String url = buildUrl(baseUrl, requestEntity);

    if (logger.isDebugEnabled()) {
        if (requestEntity.type == RequestType.POST || requestEntity.type == RequestType.PUT
                || requestEntity.type == RequestType.PATCH) {
            logger.debug("[REQ]http-{}: url={}, headers={}, body={}",
                    new Object[] { requestEntity.type, url, requestEntity.headers, requestEntity.bodyText });
        } else {
            logger.debug("[REQ]http-{}: url={}, headers={}",
                    new Object[] { requestEntity.type, url, requestEntity.headers });
        }
    }

    HttpRequestBase request = null;
    switch (requestEntity.type) {
    case GET:
        request = new HttpGet(url);
        break;
    case POST:
        HttpPost post = new HttpPost(url);
        configureBodyParams(requestEntity, post);
        request = post;
        break;
    case PUT:
        HttpPut put = new HttpPut(url);
        configureBodyParams(requestEntity, put);
        request = put;
        break;
    case PATCH:
        HttpPatch patch = new HttpPatch(url);
        configureBodyParams(requestEntity, patch);
        request = patch;
        break;
    case HEAD:
        request = new HttpHead(url);
        break;
    case DELETE:
        request = new HttpDelete(url);
        break;
    }

    // common-header
    String userAgent = "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.1; +http://mt.orz.at/)";
    request.setHeader("User-Agent", userAgent);

    // optinal-headers
    if (requestEntity.headers != null) {
        for (Entry<String, Object> keyValue : requestEntity.headers.entrySet()) {
            request.setHeader(keyValue.getKey(), keyValue.getValue().toString());
        }
    }

    // Basic Auth
    Credentials credentials = null;
    if (requestEntity.username != null && requestEntity.password != null) {
        credentials = new UsernamePasswordCredentials(requestEntity.username, requestEntity.password);
    } else if (configure.getUser() != null && configure.getPassword() != null) {
        credentials = new UsernamePasswordCredentials(configure.getUser(), configure.getPassword());
    }
    if (credentials != null) {
        BasicScheme basicScheme = new BasicScheme();
        try {
            request.addHeader(basicScheme.authenticate(credentials, request, null));
        } catch (AuthenticationException e) {
            throw new ArangoException(e);
        }
    }

    if (this.getHttpMode().equals(HttpMode.ASYNC)) {
        request.addHeader("x-arango-async", "store");
    } else if (this.getHttpMode().equals(HttpMode.FIREANDFORGET)) {
        request.addHeader("x-arango-async", "true");
    }
    // CURL/httpie Logger
    if (configure.isEnableCURLLogger()) {
        CURLLogger.log(url, requestEntity, userAgent, credentials);
    }
    HttpResponse response = null;
    if (preDefinedResponse != null) {
        return preDefinedResponse;
    }
    try {
        response = client.execute(request);
        if (response == null) {
            return null;
        }

        HttpResponseEntity responseEntity = new HttpResponseEntity();

        // http status
        StatusLine status = response.getStatusLine();
        responseEntity.statusCode = status.getStatusCode();
        responseEntity.statusPhrase = status.getReasonPhrase();

        logger.debug("[RES]http-{}: statusCode={}", requestEntity.type, responseEntity.statusCode);

        // ??
        // // TODO etag???
        Header etagHeader = response.getLastHeader("etag");
        if (etagHeader != null) {
            responseEntity.etag = Long.parseLong(etagHeader.getValue().replace("\"", ""));
        }
        // Map???
        responseEntity.headers = new TreeMap<String, String>();
        for (Header header : response.getAllHeaders()) {
            responseEntity.headers.put(header.getName(), header.getValue());
        }

        // ???
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            Header contentType = entity.getContentType();
            if (contentType != null) {
                responseEntity.contentType = contentType.getValue();
                if (responseEntity.isDumpResponse()) {
                    responseEntity.stream = entity.getContent();
                    logger.debug("[RES]http-{}: stream, {}", requestEntity.type, contentType.getValue());
                }
            }
            // Close stream in this method.
            if (responseEntity.stream == null) {
                responseEntity.text = IOUtils.toString(entity.getContent());
                logger.debug("[RES]http-{}: text={}", requestEntity.type, responseEntity.text);
            }
        }

        if (this.getHttpMode().equals(HttpMode.ASYNC)) {
            Map<String, String> map = responseEntity.getHeaders();
            this.addJob(map.get("X-Arango-Async-Id"), this.getCurrentObject());
        } else if (this.getHttpMode().equals(HttpMode.FIREANDFORGET)) {
            return null;
        }

        return responseEntity;
    } catch (SocketException ex) {
        throw ex;
    } catch (ClientProtocolException e) {
        throw new ArangoException(e);
    } catch (IOException e) {
        throw new ArangoException(e);
    }
}

From source file:com.liferay.mobile.android.auth.basic.BasicAuthentication.java

@Override
public void authenticate(HttpRequest request) {
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

    Header header = BasicScheme.authenticate(credentials, "UTF-8", false);
    request.addHeader(header);/*from  w  w  w .j a v a 2 s .com*/
}

From source file:net.rcarz.jiraclient.BasicCredentials.java

/**
 * Sets the Authorization header for the given request.
 *
 * @param req HTTP request to authenticate
 *///from w  ww.  j  av a 2 s . c  om
public void authenticate(HttpRequest req) {
    Credentials creds = new UsernamePasswordCredentials(username, password);
    req.addHeader(BasicScheme.authenticate(creds, "utf-8", false));
}