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

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

Introduction

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

Prototype

public AuthScope(final String host, final int port, final String realm) 

Source Link

Document

Creates a new credentials scope for the given host, port, realm, and any authentication scheme.

Usage

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

protected HttpResponse executeKerberosDispatch(HttpUriRequest outboundRequest, DefaultHttpClient client)
        throws IOException, ClientProtocolException {
    //DefaultHttpClient client = new DefaultHttpClient();
    SPNegoSchemeFactory spNegoSF = new SPNegoSchemeFactory(/* stripPort */true);
    // spNegoSF.setSpengoGenerator(new BouncySpnegoTokenGenerator());
    client.getAuthSchemes().register(AuthPolicy.SPNEGO, spNegoSF);
    client.getCredentialsProvider().setCredentials(new AuthScope(/* host */null, /* port */-1, /* realm */null),
            EMPTY_JAAS_CREDENTIALS);/* www.  j ava2  s.  c  o  m*/
    return client.execute(outboundRequest);
}

From source file:org.muckebox.android.net.MuckeboxHttpClient.java

private void addCredentials() {
    String password = Preferences.getServerPassword();

    if (password != null && password.length() > 0) {
        mHttpClient.getCredentialsProvider().setCredentials(
                new AuthScope(Preferences.getServerAddress(), Preferences.getServerPort(), "muckebox"),
                new UsernamePasswordCredentials("muckebox", password));

        mContext = new BasicHttpContext();

        BasicScheme basicAuth = new BasicScheme();
        mContext.setAttribute("preemptive-auth", basicAuth);

        mHttpClient.addRequestInterceptor(new PreemptiveAuth(), 0);
    }//from  ww  w  . j  a va2  s  . com
}

From source file:org.apache.ambari.server.controller.internal.AppCookieManager.java

/**
 * Returns hadoop.auth cookie, doing needed SPNego authentication
 * //from  ww w .j a v a 2 s . c  o m
 * @param endpoint
 *          the URL of the Hadoop service
 * @param refresh
 *          flag indicating wehther to refresh the cookie, if
 *          <code>true</code>, we do a new SPNego authentication and refresh
 *          the cookie even if the cookie already exists in local cache
 * @return hadoop.auth cookie value
 * @throws IOException
 *           in case of problem getting hadoop.auth cookie
 */
public String getAppCookie(String endpoint, boolean refresh) throws IOException {

    HttpUriRequest outboundRequest = new HttpGet(endpoint);
    URI uri = outboundRequest.getURI();
    String scheme = uri.getScheme();
    String host = uri.getHost();
    int port = uri.getPort();
    String path = uri.getPath();
    if (!refresh) {
        String appCookie = endpointCookieMap.get(endpoint);
        if (appCookie != null) {
            return appCookie;
        }
    }

    clearAppCookie(endpoint);

    DefaultHttpClient client = new DefaultHttpClient();
    SPNegoSchemeFactory spNegoSF = new SPNegoSchemeFactory(/* stripPort */true);
    // spNegoSF.setSpengoGenerator(new BouncySpnegoTokenGenerator());
    client.getAuthSchemes().register(AuthPolicy.SPNEGO, spNegoSF);
    client.getCredentialsProvider().setCredentials(new AuthScope(/* host */null, /* port */-1, /* realm */null),
            EMPTY_JAAS_CREDENTIALS);

    String hadoopAuthCookie = null;
    HttpResponse httpResponse = null;
    try {
        HttpHost httpHost = new HttpHost(host, port, scheme);
        HttpRequest httpRequest = new HttpOptions(path);
        httpResponse = client.execute(httpHost, httpRequest);
        Header[] headers = httpResponse.getHeaders(SET_COOKIE);
        hadoopAuthCookie = getHadoopAuthCookieValue(headers);
        if (hadoopAuthCookie == null) {
            LOG.error("SPNego authentication failed, can not get hadoop.auth cookie for URL: " + endpoint);
            throw new IOException("SPNego authentication failed, can not get hadoop.auth cookie");
        }
    } finally {
        if (httpResponse != null) {
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                entity.getContent().close();
            }
        }

    }

    hadoopAuthCookie = HADOOP_AUTH_EQ + quote(hadoopAuthCookie);
    setAppCookie(endpoint, hadoopAuthCookie);
    if (LOG.isInfoEnabled()) {
        LOG.info("Successful SPNego authentication to URL:" + uri.toString());
    }
    return hadoopAuthCookie;
}

From source file:org.kaaproject.kaa.server.flume.sink.hdfs.AvroSchemaSource.java

private void initHttpRestClient() {
    httpClient = new DefaultHttpClient();
    restHost = new HttpHost(kaaRestHost, kaaRestPort, "http");

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(restHost, basicAuth);/*from  w  ww  . j a v  a  2 s .  com*/

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(kaaRestHost, kaaRestPort, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(kaaRestUser, kaaRestPassword));

    httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);

}

From source file:org.apache.hadoop.gateway.dispatch.AppCookieManager.java

/**
 * Fetches hadoop.auth cookie from hadoop service authenticating using SpNego
 * /*from  w w  w.  j a  v a 2 s .c o m*/
 * @param outboundRequest
 *          out going request
 * @param refresh
 *          flag indicating whether to refresh the cached cookie
 * @return hadoop.auth cookie from hadoop service authenticating using SpNego
 * @throws IOException
 *           in case of errors
 */
public String getAppCookie(HttpUriRequest outboundRequest, boolean refresh) throws IOException {

    URI uri = outboundRequest.getURI();
    String scheme = uri.getScheme();
    String host = uri.getHost();
    int port = uri.getPort();
    if (!refresh) {
        if (appCookie != null) {
            return appCookie;
        }
    }

    DefaultHttpClient client = new DefaultHttpClient();
    SPNegoSchemeFactory spNegoSF = new SPNegoSchemeFactory(/* stripPort */true);
    // spNegoSF.setSpengoGenerator(new BouncySpnegoTokenGenerator());
    client.getAuthSchemes().register(AuthPolicy.SPNEGO, spNegoSF);
    client.getCredentialsProvider().setCredentials(new AuthScope(/* host */null, /* port */-1, /* realm */null),
            EMPTY_JAAS_CREDENTIALS);

    clearAppCookie();
    String hadoopAuthCookie = null;
    HttpResponse httpResponse = null;
    try {
        HttpHost httpHost = new HttpHost(host, port, scheme);
        HttpRequest httpRequest = createKerberosAuthenticationRequest(outboundRequest);
        httpResponse = client.execute(httpHost, httpRequest);
        Header[] headers = httpResponse.getHeaders(SET_COOKIE);
        hadoopAuthCookie = getHadoopAuthCookieValue(headers);
        EntityUtils.consume(httpResponse.getEntity());
        if (hadoopAuthCookie == null) {
            LOG.failedSPNegoAuthn(uri.toString());
            auditor.audit(Action.AUTHENTICATION, uri.toString(), ResourceType.URI, ActionOutcome.FAILURE);
            throw new IOException("SPNego authn failed, can not get hadoop.auth cookie");
        }
    } finally {
        if (httpResponse != null) {
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                entity.getContent().close();
            }
        }

    }
    LOG.successfulSPNegoAuthn(uri.toString());
    auditor.audit(Action.AUTHENTICATION, uri.toString(), ResourceType.URI, ActionOutcome.SUCCESS);
    hadoopAuthCookie = HADOOP_AUTH_EQ + quote(hadoopAuthCookie);
    setAppCookie(hadoopAuthCookie);
    return appCookie;
}

From source file:org.jboss.as.test.integration.management.console.XFrameOptionsHeaderTestCase.java

private CredentialsProvider createCredentialsProvider(URL url) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(Authentication.USERNAME,
            Authentication.PASSWORD);/*from w  ww  . j  a v  a  2 s .co m*/
    credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort(), "ManagementRealm"),
            credentials);
    return credentialsProvider;
}

From source file:org.apache.kylin.engine.mr.common.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;
    }//  ww  w. j  a v  a 2 s  .c  om
    boolean skipPortAtKerberosDatabaseLookup = true;
    System.setProperty("java.security.krb5.conf", krb5ConfigPath);
    System.setProperty("sun.security.krb5.debug", "true");
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

    DefaultHttpClient client = new DefaultHttpClient();
    AuthSchemeRegistry authSchemeRegistry = new AuthSchemeRegistry();
    authSchemeRegistry.register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory(skipPortAtKerberosDatabaseLookup));
    client.setAuthSchemes(authSchemeRegistry);

    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);
    client.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 {
            HttpResponse httpResponse = client.execute(httpget);
            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(), Charset.defaultCharset());
                logger.debug("Job " + mrJobId + " get status check result.\n");
            } else {
                url = redirect;
                logger.debug("Job " + mrJobId + " check redirect url " + url + ".\n");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.error(e.getMessage());
        } finally {
            httpget.releaseConnection();
        }
    }

    return response;
}

From source file:org.flowable.mule.MuleSendActivityBehavior.java

public void execute(DelegateExecution execution) {
    String endpointUrlValue = this.getStringFromField(this.endpointUrl, execution);
    String languageValue = this.getStringFromField(this.language, execution);
    String payloadExpressionValue = this.getStringFromField(this.payloadExpression, execution);
    String resultVariableValue = this.getStringFromField(this.resultVariable, execution);
    String usernameValue = this.getStringFromField(this.username, execution);
    String passwordValue = this.getStringFromField(this.password, execution);

    boolean isFlowable5Execution = false;
    Object payload = null;/*from  w  w w. j  a  v a 2 s. c o m*/
    if ((Context.getCommandContext() != null && Flowable5Util
            .isFlowable5ProcessDefinitionId(Context.getCommandContext(), execution.getProcessDefinitionId()))
            || (Context.getCommandContext() == null
                    && Flowable5Util.getFlowable5CompatibilityHandler() != null)) {

        payload = Flowable5Util.getFlowable5CompatibilityHandler()
                .getScriptingEngineValue(payloadExpressionValue, languageValue, execution);
        isFlowable5Execution = true;

    } else {
        ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines();
        payload = scriptingEngines.evaluate(payloadExpressionValue, languageValue, execution);
    }

    if (endpointUrlValue.startsWith("vm:")) {
        LocalMuleClient client = this.getMuleContext().getClient();
        MuleMessage message = new DefaultMuleMessage(payload, this.getMuleContext());
        MuleMessage resultMessage;
        try {
            resultMessage = client.send(endpointUrlValue, message);
        } catch (MuleException e) {
            throw new RuntimeException(e);
        }
        Object result = resultMessage.getPayload();
        if (resultVariableValue != null) {
            execution.setVariable(resultVariableValue, result);
        }

    } else {

        HttpClientBuilder clientBuilder = HttpClientBuilder.create();

        if (usernameValue != null && passwordValue != null) {
            CredentialsProvider provider = new BasicCredentialsProvider();
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(usernameValue,
                    passwordValue);
            provider.setCredentials(new AuthScope("localhost", -1, "mule-realm"), credentials);
            clientBuilder.setDefaultCredentialsProvider(provider);
        }

        HttpClient client = clientBuilder.build();

        HttpPost request = new HttpPost(endpointUrlValue);

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(payload);
            oos.flush();
            oos.close();

            request.setEntity(new ByteArrayEntity(baos.toByteArray()));

        } catch (Exception e) {
            throw new FlowableException("Error setting message payload", e);
        }

        byte[] responseBytes = null;
        try {
            // execute the POST request
            HttpResponse response = client.execute(request);
            responseBytes = IOUtils.toByteArray(response.getEntity().getContent());

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // release any connection resources used by the method
            request.releaseConnection();
        }

        if (responseBytes != null) {
            try {
                ByteArrayInputStream in = new ByteArrayInputStream(responseBytes);
                ObjectInputStream is = new ObjectInputStream(in);
                Object result = is.readObject();
                if (resultVariableValue != null) {
                    execution.setVariable(resultVariableValue, result);
                }
            } catch (Exception e) {
                throw new FlowableException("Failed to read response value", e);
            }
        }
    }

    if (isFlowable5Execution) {
        Flowable5Util.getFlowable5CompatibilityHandler().leaveExecution(execution);

    } else {
        this.leave(execution);
    }
}