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

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

Introduction

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

Prototype

public BasicScheme() 

Source Link

Usage

From source file:com.microsoft.exchange.impl.http.CustomHttpComponentsMessageSender.java

/**
 * /*from   w  ww.  j a  va 2 s  . c  om*/
 * @param scheme
 * @return
 */
protected AuthScheme identifyScheme(String scheme) {
    if (new BasicScheme().getSchemeName().equalsIgnoreCase(scheme)) {
        return new BasicScheme();
    } else if (new DigestScheme().getSchemeName().equalsIgnoreCase(scheme)) {
        return new DigestScheme();
    } else {
        // fallback
        return new BasicScheme();
    }
}

From source file:org.energy_home.jemma.utils.rest.RestClient.java

public void setCredential(String hostname, int port, String username, String password) {
    HttpHost httpHost = new HttpHost(hostname, port);
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(hostname, port),
            new UsernamePasswordCredentials(username, 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(httpHost, basicAuth);//from w w  w  . j ava 2s .co  m
    // Add AuthCache to the execution context
    httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
}

From source file:com.liferay.sync.engine.session.Session.java

private BasicAuthCache _getBasicAuthCache() {
    BasicAuthCache basicAuthCache = new BasicAuthCache();

    BasicScheme basicScheme = new BasicScheme();

    basicAuthCache.put(_httpHost, basicScheme);

    return basicAuthCache;
}

From source file:com.predic8.membrane.test.AssertUtils.java

private static DefaultHttpClient getAuthenticatingHttpClient(String host, int port, String user, String pass) {
    DefaultHttpClient hc = new DefaultHttpClient();
    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.update(new BasicScheme(), creds);
                }/*from  ww w .  j  a v  a2 s.  c  om*/
            }
        }
    };
    hc.addRequestInterceptor(preemptiveAuth, 0);
    Credentials defaultcreds = new UsernamePasswordCredentials(user, pass);
    BasicCredentialsProvider bcp = new BasicCredentialsProvider();
    bcp.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds);
    hc.setCredentialsProvider(bcp);
    hc.setCookieStore(new BasicCookieStore());
    return hc;
}

From source file:edu.lternet.pasta.doi.EzidRegistrar.java

/**
 * Login to the EZID web service API system and return a valid session
 * identifier./*w w w .jav  a 2s  .  co  m*/
 * 
 * @return The EZID session id
 * @throws EzidException
 */
public void login() throws EzidException {

    String sessionId = null;

    /*
     * The following set of code sets up Preemptive Authentication for the HTTP
     * CLIENT and is done so at the warning stated within the Apache
     * Http-Components Client tutorial here:
     * http://hc.apache.org/httpcomponents-
     * client-ga/tutorial/html/authentication.html#d5e1031
     */

    HttpHost httpHost = new HttpHost(this.host, Integer.valueOf(this.port), this.protocol);
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    AuthScope authScope = new AuthScope(httpHost.getHostName(), httpHost.getPort());
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.ezidUser, this.ezidPassword);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(authScope, credentials);

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();

    // Generate BASIC scheme object and add it to the auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(httpHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    HttpGet httpGet = new HttpGet(this.getEzidUrl("/login"));

    HttpResponse response = null;
    Header[] headers = null;
    Integer statusCode = null;

    try {

        response = httpClient.execute(httpHost, httpGet, context);
        headers = response.getAllHeaders();
        statusCode = (Integer) response.getStatusLine().getStatusCode();
        logger.info("STATUS: " + statusCode.toString());

    } catch (UnsupportedEncodingException e) {
        logger.error(e);
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        logger.error(e);
        e.printStackTrace();
    } catch (IOException e) {
        logger.error(e);
        e.printStackTrace();
    } finally {
        closeHttpClient(httpClient);
    }

    if (statusCode == HttpStatus.SC_OK) {

        String headerName = null;
        String headerValue = null;

        // Loop through all headers looking for the "Set-Cookie" header.
        for (int i = 0; i < headers.length; i++) {
            headerName = headers[i].getName();

            if (headerName.equals("Set-Cookie")) {
                headerValue = headers[i].getValue();
                sessionId = this.getSessionId(headerValue);
                logger.info("Session: " + sessionId);
            }

        }

    } else {
        String gripe = "login: failed EZID login.";
        throw new EzidException(gripe);
    }

    this.sessionId = sessionId;

}

From source file:tools.devnull.boteco.client.rest.impl.DefaultRestConfiguration.java

@Override
public RestConfiguration withAuthentication(String user, String password) {
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    CredentialsProvider provider = new BasicCredentialsProvider();

    URI uri = request.getURI();/*from  ww  w. j a  va 2  s  .  c o m*/
    authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth);
    provider.setCredentials(new AuthScope(uri.getHost(), AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(user, password));

    this.context.setCredentialsProvider(provider);
    this.context.setAuthCache(authCache);

    return this;
}

From source file:ezid.EZIDService.java

/**
 * Log into the EZID service using account credentials provided by EZID. The cookie
 * returned by EZID is cached in a local CookieStore for the duration of the EZIDService,
 * and so subsequent calls using this instance of the service will function as
 * fully authenticated. An exception is thrown if authentication fails.
 *
 * @param username to identify the user account from EZID
 * @param password the secret password for this account
 *
 * @throws EZIDException if authentication fails for any reason
 *///from  w w  w  . java  2  s.c o  m
public void login(String username, String password) throws EZIDException {
    this.username = username;
    this.password = password;
    String msg;
    try {
        URI serviceUri = new URI(LOGIN_SERVICE);
        HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.getScheme());
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(username, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING....
        //System.out.println("authCache: " + authCache.toString());

        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
            public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }
            }
        };
        byte[] body = null;

        HttpGet httpget = new HttpGet(LOGIN_SERVICE);
        body = httpclient.execute(httpget, handler, localcontext);
        String message = new String(body);
        msg = parseIdentifierResponse(message);

        // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING....
        /*
                org.apache.http.client.CookieStore cookieStore = httpclient.getCookieStore();
        System.out.println("\n\nCookies : ");
        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
        System.out.println("Cookie: " + cookies.get(i));
        } */

    } catch (URISyntaxException e) {
        //System.out.println("URI SyntaxError Exception in LOGIN");
        throw new EZIDException("Bad syntax for uri: " + LOGIN_SERVICE, e);
    } catch (ClientProtocolException e) {
        //System.out.println("ClientProtocol Exception in LOGIN");
        throw new EZIDException(e);
    } catch (IOException e) {
        //System.out.println("IO Exception in LOGIN");
        throw new EZIDException(e);
    }
    //System.out.println("Seems to be a successful LOGIN, msg= " + msg.toString());
}

From source file:com.elastic.support.util.RestExec.java

public HttpClientContext getLocalContext(HttpHost httpHost) throws Exception {
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(httpHost, basicAuth);//from  ww w . ja va 2  s  .co  m

    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    return localContext;
}

From source file:edu.lternet.pasta.client.LoginClient.java

/**
 * Perform a PASTA login operation using the user's credentials. Because there
 * is not a formal PASTA login method, we will use a simple query for the Data
 * Package Manager service, which will perform the necessary user
 * authentication (this step should be replaced with a formal PASTA
 * "login service method")./*from w  w  w .  ja va2s  .c  o m*/
 * 
 * @param uid
 *          The user identifier.
 * @param password
 *          The user password.
 * 
 * @return The authentication token as a String object if the login is
 *         successful.
 */
private String login(String uid, String password) {

    String token = null;
    String username = PastaClient.composeDistinguishedName(uid);

    /*
     * The following set of code sets up Preemptive Authentication for the HTTP
     * CLIENT and is done so at the warning stated within the Apache
     * Http-Components Client tutorial here:
     * http://hc.apache.org/httpcomponents-
     * client-ga/tutorial/html/authentication.html#d5e1031
     */

    // Define host parameters
    HttpHost httpHost = new HttpHost(this.pastaHost, this.pastaPort, this.pastaProtocol);
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    // Define user authentication credentials that will be used with the host
    AuthScope authScope = new AuthScope(httpHost.getHostName(), httpHost.getPort());
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(authScope, credentials);

    // 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(httpHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    HttpGet httpGet = new HttpGet(this.LOGIN_URL);
    HttpResponse response = null;
    Header[] headers = null;
    Integer statusCode = null;

    try {

        response = httpClient.execute(httpHost, httpGet, context);
        headers = response.getAllHeaders();
        statusCode = (Integer) response.getStatusLine().getStatusCode();
        logger.info("STATUS: " + statusCode.toString());

    } catch (UnsupportedEncodingException e) {
        logger.error(e);
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        logger.error(e);
        e.printStackTrace();
    } catch (IOException e) {
        logger.error(e);
        e.printStackTrace();
    } finally {
        closeHttpClient(httpClient);
    }

    if (statusCode == HttpStatus.SC_OK) {

        String headerName = null;
        String headerValue = null;

        // Loop through all headers looking for the "Set-Cookie" header.
        for (int i = 0; i < headers.length; i++) {
            headerName = headers[i].getName();

            if (headerName.equals("Set-Cookie")) {
                headerValue = headers[i].getValue();
                token = this.getAuthToken(headerValue);
            }

        }

    }

    return token;
}

From source file:org.elasticsearch.client.RestClient.java

/**
 * Replaces the hosts that the client communicates with.
 * @see HttpHost/*  w  w w . ja  v  a 2s.co m*/
 */
public synchronized void setHosts(HttpHost... hosts) {
    if (hosts == null || hosts.length == 0) {
        throw new IllegalArgumentException("hosts must not be null nor empty");
    }
    Set<HttpHost> httpHosts = new HashSet<>();
    AuthCache authCache = new BasicAuthCache();
    for (HttpHost host : hosts) {
        Objects.requireNonNull(host, "host cannot be null");
        httpHosts.add(host);
        authCache.put(host, new BasicScheme());
    }
    this.hostTuple = new HostTuple<>(Collections.unmodifiableSet(httpHosts), authCache);
    this.blacklist.clear();
}