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

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

Introduction

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

Prototype

AuthScope ANY

To view the source code for org.apache.http.auth AuthScope ANY.

Click Source Link

Document

Default scope matching any host, port, realm and authentication scheme.

Usage

From source file:pl.llp.aircasting.util.http.HttpBuilder.java

private HttpRequestInterceptor preemptiveAuth() {
    return new HttpRequestInterceptor() {
        @Override//from   www  .ja va2 s.  c om
        public void process(HttpRequest httpRequest, HttpContext httpContext)
                throws HttpException, IOException {
            AuthState authState = (AuthState) httpContext.getAttribute(ClientContext.TARGET_AUTH_STATE);

            Credentials credentials;
            if (useLogin) {
                credentials = new UsernamePasswordCredentials(login, password);
            } else {
                credentials = new UsernamePasswordCredentials(settingsHelper.getAuthToken(), "X");
            }

            authState.setAuthScope(AuthScope.ANY);
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(credentials);
        }
    };
}

From source file:aajavafx.EmployeeController.java

public ObservableList<EmployeeProperty> getEmployee() throws IOException, JSONException, Exception {
    Employees myEmployee = new Employees();
    Managers manager = new Managers();
    Gson gson = new Gson();
    ObservableList<EmployeeProperty> employeesProperty = FXCollections.observableArrayList();
    JSONObject jo = new JSONObject();
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/employees");

    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);

    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));
    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);
        myEmployee = gson.fromJson(jo.toString(), Employees.class);
        System.out.println(myEmployee.getEmpPhone());
        employeesProperty.add(new EmployeeProperty(myEmployee.getEmpId(), myEmployee.getEmpLastname(),
                myEmployee.getEmpFirstname(), myEmployee.getEmpUsername(), myEmployee.getEmpPassword(),
                myEmployee.getEmpEmail(), myEmployee.getEmpPhone(), myEmployee.getManagersManId().getManId(),
                myEmployee.getEmpRegistered()));
    }//from  ww w.j a  v  a2  s  .c  om
    return employeesProperty;
}

From source file:org.hawkular.alerter.elasticsearch.ElasticsearchQuery.java

private CredentialsProvider checkBasicCredentials() {
    String user = properties.get(USER);
    String password = properties.get(PASS);
    if (!isEmpty(user)) {
        if (!isEmpty(password)) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
            return credentialsProvider;
        } else {/*from  w  w  w .  j a  v  a 2 s .co m*/
            log.warnf("User [%s] without password ", user);
        }
    }
    return null;
}

From source file:sachin.spider.SpiderConfig.java

private String handleRedirect(String url) {
    try {//ww w.j  a v  a 2  s.  c o m
        HttpGet httpget = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom().setRedirectsEnabled(true)
                .setCircularRedirectsAllowed(true).setRelativeRedirectsAllowed(true)
                .setConnectionRequestTimeout(getConnectionRequestTimeout()).setSocketTimeout(getSocketTimeout())
                .setConnectTimeout(getConnectionTimeout()).build();
        httpget.setConfig(requestConfig);
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setUserAgent(getUserAgentString());
        if (isAuthenticate()) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(getUsername(), getPassword()));
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }
        CloseableHttpClient httpclient = builder.build();
        HttpClientContext context = HttpClientContext.create();
        CloseableHttpResponse response = httpclient.execute(httpget, context);
        HttpHost target = context.getTargetHost();
        List<URI> redirectLocations = context.getRedirectLocations();
        URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
        url = location.toString();
        EntityUtils.consumeQuietly(response.getEntity());
        HttpClientUtils.closeQuietly(response);
    } catch (IOException | URISyntaxException ex) {
        Logger.getLogger(SpiderConfig.class.getName()).log(Level.SEVERE, null, ex);
        System.err.println(url);
    }
    return url;
}

From source file:org.sonatype.nexus.apachehttpclient.Hc4ProviderBase.java

protected void applyAuthenticationConfig(final Builder builder, final RemoteAuthenticationSettings ras,
        final HttpHost proxyHost) {
    if (ras != null) {
        String authScope = "target";
        if (proxyHost != null) {
            authScope = proxyHost.toHostString() + " proxy";
        }/*from   w  ww.ja v a2  s . c o  m*/

        final List<String> authorisationPreference = Lists.newArrayListWithExpectedSize(3);
        authorisationPreference.add(AuthSchemes.DIGEST);
        authorisationPreference.add(AuthSchemes.BASIC);
        Credentials credentials = null;
        if (ras instanceof ClientSSLRemoteAuthenticationSettings) {
            throw new IllegalArgumentException("SSL client authentication not yet supported!");
        } else if (ras instanceof NtlmRemoteAuthenticationSettings) {
            final NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras;
            // Using NTLM auth, adding it as first in policies
            authorisationPreference.add(0, AuthSchemes.NTLM);
            log.debug("{} authentication setup for NTLM domain '{}'", authScope, nras.getNtlmDomain());
            credentials = new NTCredentials(nras.getUsername(), nras.getPassword(), nras.getNtlmHost(),
                    nras.getNtlmDomain());
        } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) {
            final UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras;
            log.debug("{} authentication setup for remote storage with username '{}'", authScope,
                    uras.getUsername());
            credentials = new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword());
        }

        if (credentials != null) {
            if (proxyHost != null) {
                builder.setCredentials(new AuthScope(proxyHost), credentials);
                builder.getRequestConfigBuilder().setProxyPreferredAuthSchemes(authorisationPreference);
            } else {
                builder.setCredentials(AuthScope.ANY, credentials);
                builder.getRequestConfigBuilder().setTargetPreferredAuthSchemes(authorisationPreference);
            }
        }
    }
}

From source file:org.glassfish.jersey.apache.connector.AuthTest.java

@Test
@Ignore("JERSEY-1750: Cannot retry request with a non-repeatable request entity. How to buffer the entity?"
        + " Allow repeatable write in jersey?")
public void testAuthPost() {
    CredentialsProvider credentialsProvider = new org.apache.http.impl.client.BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("name", "password"));

    ClientConfig cc = new ClientConfig();
    cc.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);
    cc.connectorProvider(new ApacheConnectorProvider());
    Client client = ClientBuilder.newClient(cc);
    WebTarget r = client.target(getBaseUri()).path("test");

    assertEquals("POST", r.request().post(Entity.text("POST"), String.class));
}

From source file:com.microsoft.alm.provider.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);//from ww w  .j a va  2  s.c o  m

    return clientConfig;
}

From source file:com.redhat.jenkins.nodesharing.RestEndpoint.java

private @Nonnull HttpClientContext getAuthenticatingContext(@Nonnull HttpRequestBase method) {
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(URIUtils.extractHost(method.getURI()), basicAuth);

    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new org.apache.http.auth.UsernamePasswordCredentials(
            creds.getUsername(), creds.getPassword().getPlainText()));
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(provider);
    context.setAuthCache(authCache);//from  ww w .  j  a va2s . c o m
    return context;
}

From source file:org.sonatype.nexus.httpclient.config.ConfigurationCustomizer.java

/**
 * Apply authentication configuration to plan.
 *//* w ww  .j  a va 2s . co  m*/
private void apply(final AuthenticationConfiguration authentication, final HttpClientPlan plan,
        @Nullable final HttpHost proxyHost) {
    Credentials credentials;
    List<String> authSchemes;

    if (authentication instanceof UsernameAuthenticationConfiguration) {
        UsernameAuthenticationConfiguration auth = (UsernameAuthenticationConfiguration) authentication;
        authSchemes = ImmutableList.of(DIGEST, BASIC);
        credentials = new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword());
    } else if (authentication instanceof NtlmAuthenticationConfiguration) {
        NtlmAuthenticationConfiguration auth = (NtlmAuthenticationConfiguration) authentication;
        authSchemes = ImmutableList.of(NTLM, DIGEST, BASIC);
        credentials = new NTCredentials(auth.getUsername(), auth.getPassword(), auth.getHost(),
                auth.getDomain());
    } else {
        throw new IllegalArgumentException("Unsupported authentication configuration: " + authentication);
    }

    if (proxyHost != null) {
        plan.addCredentials(new AuthScope(proxyHost), credentials);
        plan.getRequest().setProxyPreferredAuthSchemes(authSchemes);
    } else {
        plan.addCredentials(AuthScope.ANY, credentials);
        plan.getRequest().setTargetPreferredAuthSchemes(authSchemes);
    }
}

From source file:org.dcache.srm.client.HttpClientSender.java

/**
 * Creates the HttpContext for a particular call to a SOAP server.
 *
 * Called once per session./*  w  ww .j  a v  a  2s  . c  om*/
 */
protected HttpClientContext createHttpContext(MessageContext msgContext, URI uri) {
    HttpClientContext context = new HttpClientContext(new BasicHttpContext());
    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();
    if ((userID == null) && (uri.getUserInfo() != null)) {
        String info = uri.getUserInfo();
        int sep = info.indexOf(':');
        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        // if the username is in the form "user\domain"
        // then use NTCredentials instead.
        int domainIndex = userID.indexOf('\\');
        if (domainIndex > 0 && userID.length() > domainIndex + 1) {
            String domain = userID.substring(0, domainIndex);
            String user = userID.substring(domainIndex + 1);
            credsProvider.setCredentials(AuthScope.ANY,
                    new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain));
        } else {
            credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userID, passwd));
        }
        context.setCredentialsProvider(credsProvider);
    }
    context.setAttribute(HttpClientTransport.TRANSPORT_HTTP_CREDENTIALS,
            msgContext.getProperty(HttpClientTransport.TRANSPORT_HTTP_CREDENTIALS));
    return context;
}