Java Code Examples for org.apache.http.auth.AuthScope#ANY_REALM

The following examples show how to use org.apache.http.auth.AuthScope#ANY_REALM . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebServicesClientTest.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
public static void checkUserCredentials(String username, String password, AuthScheme authScheme) throws NoSuchFieldException,
    IllegalAccessException
{
  CredentialsProvider provider = getCredentialsProvider();
  String httpScheme = AuthScope.ANY_SCHEME;
  if (authScheme == AuthScheme.BASIC) {
    httpScheme = AuthSchemes.BASIC;
  } else if (authScheme == AuthScheme.DIGEST) {
    httpScheme = AuthSchemes.DIGEST;
  }
  AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, httpScheme);
  Credentials credentials = provider.getCredentials(authScope);
  Assert.assertNotNull("Credentials", credentials);
  Assert.assertTrue("Credentials type is user", UsernamePasswordCredentials.class.isAssignableFrom(credentials.getClass()));
  UsernamePasswordCredentials pwdCredentials = (UsernamePasswordCredentials)credentials;
  Assert.assertEquals("Username", username, pwdCredentials.getUserName());
  Assert.assertEquals("Password", password, pwdCredentials.getPassword());
}
 
Example 2
Source File: WebAuthentication.java    From fess with Apache License 2.0 6 votes vote down vote up
private AuthScope getAuthScope() {
    if (StringUtil.isBlank(getHostname())) {
        return AuthScope.ANY;
    }

    int p;
    if (getPort() == null) {
        p = AuthScope.ANY_PORT;
    } else {
        p = getPort();
    }

    String r = getAuthRealm();
    if (StringUtil.isBlank(r)) {
        r = AuthScope.ANY_REALM;
    }

    String s = getProtocolScheme();
    if (StringUtil.isBlank(s) || Constants.NTLM.equals(s)) {
        s = AuthScope.ANY_SCHEME;
    }

    return new AuthScope(getHostname(), p, r, s);
}
 
Example 3
Source File: WebServicesClient.java    From Bats with Apache License 2.0 5 votes vote down vote up
private static void setupUserPassAuthScheme(AuthScheme scheme, String httpScheme, AuthSchemeProvider provider, ConfigProvider configuration)
{
  String username = configuration.getProperty(scheme, "username");
  String password = configuration.getProperty(scheme, "password");
  if ((username != null) && (password != null)) {
    LOG.info("Setting up scheme {}", scheme);
    AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, httpScheme);
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    setupHttpAuthScheme(httpScheme, provider, authScope, credentials);
  } else if ((username != null) || (password != null)) {
    LOG.warn("Not setting up scheme {}, missing credentials {}", scheme, (username == null) ? "username" : "password");
  }
}
 
Example 4
Source File: TestHttpClient4.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
private CredentialsProvider getProxyCredentialProvider() {
    String proxyHost = Settings.getProperty("davmail.proxyHost");
    int proxyPort = Settings.getIntProperty("davmail.proxyPort");

    // proxy authentication
    String proxyUser = Settings.getProperty("davmail.proxyUser");
    String proxyPassword = Settings.getProperty("davmail.proxyPassword");
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    AuthScope authScope = new AuthScope(proxyHost, proxyPort, AuthScope.ANY_REALM);
    credentialsProvider.setCredentials(authScope, new UsernamePasswordCredentials(proxyUser, proxyPassword));
    return credentialsProvider;
}
 
Example 5
Source File: WebServicesClient.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
private static void setupUserPassAuthScheme(AuthScheme scheme, String httpScheme, AuthSchemeProvider provider, ConfigProvider configuration)
{
  String username = configuration.getProperty(scheme, "username");
  String password = configuration.getProperty(scheme, "password");
  if ((username != null) && (password != null)) {
    LOG.info("Setting up scheme {}", scheme);
    AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, httpScheme);
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    setupHttpAuthScheme(httpScheme, provider, authScope, credentials);
  } else if ((username != null) || (password != null)) {
    LOG.warn("Not setting up scheme {}, missing credentials {}", scheme, (username == null) ? "username" : "password");
  }
}
 
Example 6
Source File: JenkinsHttpClient.java    From verigreen with Apache License 2.0 5 votes vote down vote up
/**
 * Create an authenticated Jenkins HTTP client
 * 
 * @param uri
 *            Location of the jenkins server (ex. http://localhost:8080)
 * @param username
 *            Username to use when connecting
 * @param password
 *            Password or auth token to use when connecting
 */
public JenkinsHttpClient(URI uri, String username, String password) {
    this(uri);
    if (isNotBlank(username)) {
        CredentialsProvider provider = client.getCredentialsProvider();
        AuthScope scope = new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM);
        UsernamePasswordCredentials credentials =
                new UsernamePasswordCredentials(username, password);
        provider.setCredentials(scope, credentials);
        
        localContext = new BasicHttpContext();
        localContext.setAttribute("preemptive-auth", new BasicScheme());
        client.addRequestInterceptor(new PreemptiveAuth(), 0);
    }
}
 
Example 7
Source File: HTTPAuthUtil.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
static public AuthScope hostToAuthScope(HttpHost host) {
  return new AuthScope(host.getHostName(), host.getPort(), AuthScope.ANY_REALM, AuthScope.ANY_SCHEME);
}
 
Example 8
Source File: RestClientHelper.java    From azure-devops-intellij with MIT License 4 votes vote down vote up
public static ClientConfig getClientConfig(final ServerContext.Type type,
                                           final Credentials credentials,
                                           final String serverUri,
                                           final boolean includeProxySettings) {

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);

    final ConnectorProvider connectorProvider = new ApacheConnectorProvider();
    // custom json provider ignores new fields that aren't recognized
    final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    final ClientConfig clientConfig = new ClientConfig(jacksonJsonProvider).connectorProvider(connectorProvider);
    clientConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);
    clientConfig.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

    // For TFS OnPrem we only support NTLM authentication right now. Since 2016 servers support Basic as well,
    // we need to let the server and client negotiate the protocol instead of preemptively assuming Basic.
    // TODO: This prevents PATs from being used OnPrem. We need to fix this soon to support PATs onPrem.
    clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, type != ServerContext.Type.TFS);

    //Define a local HTTP proxy
    if (includeProxySettings) {
        final HttpProxyService proxyService = PluginServiceProvider.getInstance().getHttpProxyService();
        final String proxyUrl = proxyService.getProxyURL();
        clientConfig.property(ClientProperties.PROXY_URI, proxyUrl);
        if (proxyService.isAuthenticationRequired()) {
            // To work with authenticated proxies and TFS, we provide the proxy credentials if they are registered
            final AuthScope ntlmAuthScope =
                    new AuthScope(proxyService.getProxyHost(), proxyService.getProxyPort(),
                            AuthScope.ANY_REALM, AuthScope.ANY_SCHEME);
            credentialsProvider.setCredentials(ntlmAuthScope,
                    new UsernamePasswordCredentials(proxyService.getUserName(), proxyService.getPassword()));
        }
    }

    // register a filter to set the User Agent header
    clientConfig.register(new ClientRequestFilter() {
        @Override
        public void filter(final ClientRequestContext requestContext) throws IOException {
            // The default user agent is something like "Jersey/2.6"
            final String userAgent = VersionInfo.getUserAgent("Apache-HttpClient", "org.apache.http.client", HttpClientBuilder.class);
            // Finally, we can add the header
            requestContext.getHeaders().add(HttpHeaders.USER_AGENT, userAgent);
        }
    });

    return clientConfig;
}
 
Example 9
Source File: ApiClient.java    From spring-hmac-rest with MIT License 4 votes vote down vote up
public <I, O extends AbstractResponseWrapper<I>> O echo(I request, Class<O> clazz) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        final AuthScope authScope = new AuthScope(host, port, AuthScope.ANY_REALM, scheme);
        final Credentials credentials = credentialsProvider.getCredentials(authScope);

        if (credentials == null) {
            throw new RuntimeException("Can't find credentials for AuthScope: " + authScope);
        }

        String apiKey = credentials.getUserPrincipal().getName();
        String apiSecret = credentials.getPassword();

        String nonce = UUID.randomUUID().toString();

        headers.setDate(clock.millis());
        String dateString = headers.getFirst(HttpHeaders.DATE);

        RequestWrapper<I> requestWrapper = new RequestWrapper<>(request);
        requestWrapper.setData(request);

        final String valueAsString;
        try {
            valueAsString = objectMapper.writeValueAsString(requestWrapper);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        final String resource = "/api/echo";
        final HmacSignatureBuilder signatureBuilder = new HmacSignatureBuilder()
                .scheme(scheme)
                .host(host+":" + port)
                .method("POST")
                .resource(resource)
                .apiKey(apiKey)
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .nonce(nonce)
                .date(dateString)
                .apiSecret(apiSecret)
                .payload(valueAsString.getBytes(StandardCharsets.UTF_8));
        final String signature = signatureBuilder
                .buildAsBase64String();

        final String authHeader = signatureBuilder.getAlgorithm() + " " + apiKey + ":" + nonce + ":" + signature;
        headers.add(HttpHeaders.AUTHORIZATION, authHeader);

        headers.add(HttpHeaders.USER_AGENT, USER_AGENT);

        HttpEntity<String> entity = new HttpEntity<>(valueAsString, headers);

        final O payloadWrapper = restTemplate.postForObject(
                scheme + "://" + host + ":" + port + resource,
                entity,
                clazz);

        return payloadWrapper;
    }
 
Example 10
Source File: DefaultCredentialsProvider.java    From htmlunit with Apache License 2.0 3 votes vote down vote up
/**
 * Adds NTLM credentials for the specified username/password on the specified host/port.
 * @param username the username for the new credentials; should not include the domain to authenticate with;
 *        for example: <tt>"user"</tt> is correct whereas <tt>"DOMAIN\\user"</tt> is not
 * @param password the password for the new credentials
 * @param host the host to which to the new credentials apply ({@code null} if applicable to any host)
 * @param port the port to which to the new credentials apply (negative if applicable to any port)
 * @param workstation The workstation the authentication request is originating from.
 *        Essentially, the computer name for this machine.
 * @param domain the domain to authenticate within
 */
public void addNTLMCredentials(final String username, final String password, final String host,
        final int port, final String workstation, final String domain) {
    final AuthScope authscope = new AuthScope(host, port, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME);
    final Credentials credentials = new NTCredentials(username, password, workstation, domain);
    setCredentials(authscope, credentials);
}
 
Example 11
Source File: HTTPAuthUtil.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Create an AuthScope from a URI; remove any principal
 *
 * @param uri to convert
 * @returns an AuthScope instance
 */

static AuthScope uriToAuthScope(URI uri) {
  assert (uri != null);
  return new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM, AuthScope.ANY_SCHEME);
}