org.apache.http.auth.AuthScope Java Examples

The following examples show how to use org.apache.http.auth.AuthScope. 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: HttpTransportFactory.java    From hadoop-connectors with Apache License 2.0 7 votes vote down vote up
/**
 * Create an {@link ApacheHttpTransport} for calling Google APIs with an optional HTTP proxy.
 *
 * @param proxyUri Optional HTTP proxy URI to use with the transport.
 * @param proxyCredentials Optional HTTP proxy credentials to authenticate with the transport
 *     proxy.
 * @return The resulting HttpTransport.
 * @throws IOException If there is an issue connecting to Google's certification server.
 * @throws GeneralSecurityException If there is a security issue with the keystore.
 */
public static ApacheHttpTransport createApacheHttpTransport(
    @Nullable URI proxyUri, @Nullable Credentials proxyCredentials)
    throws IOException, GeneralSecurityException {
  checkArgument(
      proxyUri != null || proxyCredentials == null,
      "if proxyUri is null than proxyCredentials should be null too");

  ApacheHttpTransport transport =
      new ApacheHttpTransport.Builder()
          .trustCertificates(GoogleUtils.getCertificateTrustStore())
          .setProxy(
              proxyUri == null ? null : new HttpHost(proxyUri.getHost(), proxyUri.getPort()))
          .build();

  if (proxyCredentials != null) {
    ((DefaultHttpClient) transport.getHttpClient())
        .getCredentialsProvider()
        .setCredentials(new AuthScope(proxyUri.getHost(), proxyUri.getPort()), proxyCredentials);
  }

  return transport;
}
 
Example #2
Source File: HttpGenericOperationUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) {
    try {
        SSLContext sslContext = SSLContexts.createDefault();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionSocketFactory)
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .build();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST),
                new UsernamePasswordCredentials(username, password));
        PoolingHttpClientConnectionManager connectionPool = new PoolingHttpClientConnectionManager(registry);
        HttpClientBuilder.create().setConnectionManager(connectionPool).build();
        return HttpClientBuilder.create()
                .setConnectionManager(connectionPool)
                .setRetryHandler(new StandardHttpRequestRetryHandler(5, true))
                .setDefaultCredentialsProvider(credsProvider).build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #3
Source File: DefaultCredentialsProvider.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Find matching {@link Credentials credentials} for the given authentication scope.
 *
 * @param map the credentials hash map
 * @param authscope the {@link AuthScope authentication scope}
 * @return the credentials
 */
private static Credentials matchCredentials(final Map<AuthScopeProxy, Credentials> map, final AuthScope authscope) {
    Credentials creds = map.get(new AuthScopeProxy(authscope));
    if (creds == null) {
        int bestMatchFactor = -1;
        AuthScopeProxy bestMatch = null;
        for (final AuthScopeProxy proxy : map.keySet()) {
            final AuthScope current = proxy.getAuthScope();
            final int factor = authscope.match(current);
            if (factor > bestMatchFactor) {
                bestMatchFactor = factor;
                bestMatch = proxy;
            }
        }
        if (bestMatch != null) {
            creds = map.get(bestMatch);
        }
    }
    return creds;
}
 
Example #4
Source File: ElasticsearchRestClientInstrumentationIT.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void startElasticsearchContainerAndClient() throws IOException {
    // Start the container
    container = new ElasticsearchContainer(ELASTICSEARCH_CONTAINER_VERSION);
    container.start();

    // Create the client
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER_NAME, PASSWORD));

    RestClientBuilder builder = RestClient.builder(HttpHost.create(container.getHttpHostAddress()))
        .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
    client = new RestHighLevelClient(builder);

    client.indices().create(new CreateIndexRequest(INDEX), RequestOptions.DEFAULT);
    reporter.reset();
}
 
Example #5
Source File: RestRequestByHttpClient.java    From activiti-in-action-codes with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {

        // 设置Base Auth验证信息
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("kermit", "kermit");
        provider.setCredentials(AuthScope.ANY, credentials);

        // 创建HttpClient
        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

        // 发送请求
        HttpResponse response = client.execute(new HttpGet(REST_URI));
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String content = EntityUtils.toString(entity, "UTF-8");
            System.out.println(content);
        }
    }
 
Example #6
Source File: HDInsightInstance.java    From reef with Apache License 2.0 6 votes vote down vote up
private HttpClientContext getClientContext(final String hostname, final String username, final String password)
    throws IOException {
  final HttpHost targetHost = new HttpHost(hostname, 443, "https");
  final HttpClientContext result = HttpClientContext.create();

  // Setup credentials provider
  final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

  credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
  result.setCredentialsProvider(credentialsProvider);

  // Setup preemptive authentication
  final AuthCache authCache = new BasicAuthCache();
  final BasicScheme basicAuth = new BasicScheme();
  authCache.put(targetHost, basicAuth);
  result.setAuthCache(authCache);
  final HttpGet httpget = new HttpGet("/");

  // Prime the cache
  try (CloseableHttpResponse response = this.httpClient.execute(targetHost, httpget, result)) {
    // empty try block used to automatically close resources
  }
  return result;
}
 
Example #7
Source File: Utils.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
public static String httpAuthPOST(String url, String user, String password, String agent, String type, String data) throws Exception {
	HttpPost request = new HttpPost(url);
	request.setHeader("User-Agent", agent);
	StringEntity params = new StringEntity(data, "utf-8");
	request.addHeader("content-type", type);
	request.setEntity(params);
	HttpParams httpParams = new BasicHttpParams();
	HttpConnectionParams.setConnectionTimeout(httpParams, URL_TIMEOUT);
	HttpConnectionParams.setSoTimeout(httpParams, URL_TIMEOUT);
	DefaultHttpClient client = new DefaultHttpClient(httpParams);
	client.getCredentialsProvider().setCredentials(
			new AuthScope(AuthScope.ANY),
			new UsernamePasswordCredentials(user, password));
	HttpResponse response = client.execute(request);
	return fetchResponse(response);
}
 
Example #8
Source File: HelmPublish.java    From gradle-plugins with Apache License 2.0 6 votes vote down vote up
private CredentialsProvider getCredentialsProvider() {
	Project project = getProject();
	HelmExtension extension = project.getExtensions().getByType(HelmExtension.class);
	String helmUser = extension.getCredentials().getUser();
	String helmPass = extension.getCredentials().getPass();
	if (helmUser == null) {
		throw new IllegalArgumentException("deployment.helmUser not specified");
	}
	if (helmPass == null) {
		throw new IllegalArgumentException("deployment.helmPass not specified");
	}
	CredentialsProvider provider = new BasicCredentialsProvider();
	UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(helmUser, helmPass);
	provider.setCredentials(AuthScope.ANY, credentials);
	return provider;
}
 
Example #9
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testSwagger() throws Exception {
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/services/rs/swagger.json";

    String user = "alice";
    String password = "ecila";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(user, password));

    final UnexpectedPage swaggerPage = webClient.getPage(url);
    WebResponse response = swaggerPage.getWebResponse();
    Assert.assertEquals("application/json", response.getContentType());
    String json = response.getContentAsString();
    Assert.assertTrue(json.contains("Claims"));

    webClient.close();
}
 
Example #10
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 #11
Source File: DownloadHttpArtifact.java    From vertx-deploy-tools with Apache License 2.0 6 votes vote down vote up
@Override
public Observable<T> executeAsync(T request) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials
            = new UsernamePasswordCredentials(config.getHttpAuthUser(), config.getHttpAuthPassword());
    provider.setCredentials(AuthScope.ANY, credentials);
    final URI location = config.getNexusUrl().resolve(config.getNexusUrl().getPath() + "/" + request.getRemoteLocation());
    try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build()) {
        LOG.info("[{} - {}]: Downloaded artifact {} to {}.", logConstant, request.getId(), request.getModuleId(), request.getLocalPath(config.getArtifactRepo()));
        HttpUriRequest get = new HttpGet(location);
        CloseableHttpResponse response = client.execute(get);
        response.getEntity().writeTo(new FileOutputStream(request.getLocalPath(config.getArtifactRepo()).toFile()));
    } catch (IOException e) {
        LOG.error("[{} - {}]: Error downloading artifact -> {}, {}", logConstant, request.getId(), e.getMessage(), e);
        throw new IllegalStateException(e);
    }
    return just(request);
}
 
Example #12
Source File: TestUrlCreds.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testUrlCredDefaultProvider() throws HTTPException {
  String url = "https://" + username + ":" + password + "@" + host + "/something/garbage.grb?query";
  logger.info("Testing {}", url);
  try (HTTPMethod method = HTTPFactory.Get(url)) {
    // we should have a default BasicCredentialProvider available, even though
    // we didn't call the factory with a specific provider
    HTTPSession session = method.getSession();
    CredentialsProvider credentialsProvider = session.sessionprovider;
    assertThat(credentialsProvider).isNotNull();
    AuthScope expectedAuthScope = new AuthScope(host, 80);
    Credentials credentials = credentialsProvider.getCredentials(expectedAuthScope);
    assertThat(credentials).isNotNull();
    assertThat(credentials.getUserPrincipal().getName()).isEqualTo(username);
    assertThat(credentials.getPassword()).isEqualTo(password);
  }
}
 
Example #13
Source File: HttpDispatcher.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static HttpDispatcher getInstance(String uri, Credentials credentials) {

        HttpDispatcher dispatcher = new HttpDispatcher(new HttpHost(uri),
                new BasicHttpContext());

        CredentialsProvider credsProvider = new BasicCredentialsProvider();

        AuthScope authScope = new AuthScope(
                dispatcher.host.getHostName(),
                dispatcher.host.getPort());

        credsProvider.setCredentials(authScope, credentials);

        ((DefaultHttpClient) dispatcher.client).getCredentialsProvider().setCredentials(
                authScope, credentials);
        return dispatcher;
    }
 
Example #14
Source File: EndpointTestSource.java    From RDFUnit with Apache License 2.0 6 votes vote down vote up
@Override
protected QueryExecutionFactory initQueryFactory() {

    QueryExecutionFactory qef;
    // if empty
    if (username.isEmpty() && password.isEmpty()) {
        qef = new QueryExecutionFactoryHttp(getSparqlEndpoint(), getSparqlGraphs());
    } else {
        DatasetDescription dd = new DatasetDescription(new ArrayList<>(getSparqlGraphs()), Collections.emptyList());
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials
                = new UsernamePasswordCredentials(username, password);
        provider.setCredentials(AuthScope.ANY, credentials);

        HttpClient client = HttpClientBuilder.create()
                .setDefaultCredentialsProvider(provider)
                .build();
        qef = new QueryExecutionFactoryHttp(getSparqlEndpoint(), dd, client);
    }

    return masqueradeQEF(qef, this);
}
 
Example #15
Source File: DefaultSpringCloudConfigClientGateway.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private HttpClientContext setupContext() {
    final HttpClientContext context = HttpClientContext.create();
    if (baseUri.contains("@") || springCloudConfigClientConfig.usernameAndPasswordSet()) {
        final AuthCache authCache = InMemoryAuthCache.INSTANCE;
        authCache.put(HttpHost.create(baseUri), new BasicScheme());
        context.setAuthCache(authCache);
        if (springCloudConfigClientConfig.usernameAndPasswordSet()) {
            final CredentialsProvider provider = new BasicCredentialsProvider();
            final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                    springCloudConfigClientConfig.username.get(), springCloudConfigClientConfig.password.get());
            provider.setCredentials(AuthScope.ANY, credentials);
            context.setCredentialsProvider(provider);
        }
    }
    return context;
}
 
Example #16
Source File: HttpClientUtil.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Returns context with AuthCache or null in case of any exception was thrown.
 *
 * @param host
 * @param port
 * @param user
 * @param password
 * @param schema
 * @return {@link org.apache.http.client.protocol.HttpClientContext HttpClientContext}
 */
public static HttpClientContext createPreemptiveBasicAuthentication( String host, int port, String user,
                                                                     String password, String schema ) {
  HttpClientContext localContext = null;
  try {
    HttpHost target = new HttpHost( host, port, schema );
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
      new AuthScope( target.getHostName(), target.getPort() ),
      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( target, basicAuth );

    // Add AuthCache to the execution context
    localContext = HttpClientContext.create();
    localContext.setAuthCache( authCache );
  } catch ( Exception e ) {
    return null;
  }
  return localContext;
}
 
Example #17
Source File: ElasticSearchFilter.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@JsonCreator
public ElasticSearchFilter(@JsonProperty("hostname") String hostname, @JsonProperty("port") int port,
                           @JsonProperty("username") Optional<String> username,
                           @JsonProperty("password") Optional<String> password) {
  Header[] headers = {
    new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"),
    new BasicHeader("Role", "Read")};
  final RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(hostname, port))
    .setDefaultHeaders(headers);
  if (username.isPresent() && !username.get().isEmpty() && password.isPresent() && !password.get().isEmpty()) {
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    credentialsProvider.setCredentials(
      AuthScope.ANY,
      new UsernamePasswordCredentials(username.get(), password.get())
    );

    restClientBuilder.setHttpClientConfigCallback(b -> b.setDefaultCredentialsProvider(credentialsProvider));
  }
  restClient = restClientBuilder.build();
  mapper = new ObjectMapper();
}
 
Example #18
Source File: CheckinWorker.java    From dummydroid with Apache License 2.0 6 votes vote down vote up
protected void setProxy(HttpClient client) throws IOException {
	File cfgfile = new File(NETCFG);
	if (cfgfile.exists()) {
		Properties cfg = new Properties();
		cfg.load(new FileInputStream(cfgfile));
		String ph = cfg.getProperty(PROXYHOST, null);
		String pp = cfg.getProperty(PROXYPORT, null);
		String pu = cfg.getProperty(PROXYUSER, null);
		String pw = cfg.getProperty(PROXYPASS, null);
		if (ph == null || pp == null) {
			return;
		}
		final HttpHost proxy = new HttpHost(ph, Integer.parseInt(pp));
		client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
		if (pu != null && pw != null) {
			((DefaultHttpClient) client).getCredentialsProvider().setCredentials(
					new AuthScope(proxy), new UsernamePasswordCredentials(pu, pw));
		}
	}
}
 
Example #19
Source File: ApiGatewayTest.java    From Inside_Android_Testing with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldMakeRemoteGetCalls() {
    Robolectric.getBackgroundScheduler().pause();

    TestGetRequest apiRequest = new TestGetRequest();
    apiGateway.makeRequest(apiRequest, responseCallbacks);

    Robolectric.addPendingHttpResponse(200, GENERIC_XML);

    Robolectric.getBackgroundScheduler().runOneTask();

    HttpRequestInfo sentHttpRequestData = Robolectric.getSentHttpRequestInfo(0);
    HttpRequest sentHttpRequest = sentHttpRequestData.getHttpRequest();
    assertThat(sentHttpRequest.getRequestLine().getUri(), equalTo("www.example.com"));
    assertThat(sentHttpRequest.getRequestLine().getMethod(), equalTo(HttpGet.METHOD_NAME));

    assertThat(sentHttpRequest.getHeaders("foo")[0].getValue(), equalTo("bar"));

    CredentialsProvider credentialsProvider =
            (CredentialsProvider) sentHttpRequestData.getHttpContext().getAttribute(ClientContext.CREDS_PROVIDER);
    assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getUserPrincipal().getName(), CoreMatchers.equalTo("spongebob"));
    assertThat(credentialsProvider.getCredentials(AuthScope.ANY).getPassword(), CoreMatchers.equalTo("squarepants"));
}
 
Example #20
Source File: ClientApiFunctionalTest.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
public static void modifyConcurrentUsersOnHttpServer(String restServerName, int numberOfUsers) throws Exception {
	DefaultHttpClient client = new DefaultHttpClient();
	client.getCredentialsProvider().setCredentials(new AuthScope(host, getAdminPort()),
			new UsernamePasswordCredentials("admin", "admin"));
	String extSecurityrName = "";
	String body = "{\"group-name\": \"Default\", \"concurrent-request-limit\":\"" + numberOfUsers + "\"}";

	HttpPut put = new HttpPut("http://" + host + ":" + admin_Port + "/manage/v2/servers/" + restServerName
			+ "/properties?server-type=http");
	put.addHeader("Content-type", "application/json");
	put.setEntity(new StringEntity(body));
	HttpResponse response2 = client.execute(put);
	HttpEntity respEntity = response2.getEntity();
	if (respEntity != null) {
		String content = EntityUtils.toString(respEntity);
		System.out.println(content);
	}
	client.getConnectionManager().shutdown();
}
 
Example #21
Source File: ProxyClientHttpRequestFactoryTest.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
@Test
public void プロキシが設定されたHttpClientが生成される() throws NoSuchFieldException, SecurityException, IllegalArgumentException,
    IllegalAccessException {
    HttpClient client = proxyFactory.getHttpClient();
    assertThat(client, CoreMatchers.notNullValue());
    CredentialsProvider provider = getCredentialsProvider(client);
    assertThat(provider, CoreMatchers.notNullValue());
    Credentials credentials = provider.getCredentials(new AuthScope("proxy.example.com", 8080));
    assertThat(credentials, CoreMatchers.notNullValue());
    assertThat(credentials.getUserPrincipal().getName(), CoreMatchers.is("userid"));
    assertThat(credentials.getPassword(), CoreMatchers.is("P@ssword!"));
}
 
Example #22
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBadWReq() throws Exception {
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/federation?";
    url += "wa=wsignin1.0";
    url += "&whr=urn:org:apache:cxf:fediz:idp:realm-A";
    url += "&wtrealm=urn:org:apache:cxf:fediz:fedizhelloworld";
    String wreply = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName() + "/secure/fedservlet";
    url += "&wreply=" + wreply;

    String testWReq =
        "<RequestSecurityToken xmlns=\"http://docs.oasis-open.org/ws-sx/ws-trust/200512\">"
        + "<TokenType>http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV3.0</TokenType>"
        + "</RequestSecurityToken>";
    url += "&wreq=" + URLEncoder.encode(testWReq, "UTF-8");

    String user = "alice";
    String password = "ecila";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    try {
        webClient.getPage(url);
        Assert.fail("Failure expected on a bad wreq value");
    } catch (FailingHttpStatusCodeException ex) {
        Assert.assertEquals(ex.getStatusCode(), 400);
    }

    webClient.close();
}
 
Example #23
Source File: ProxyUtils.java    From webdriverextensions-maven-plugin with Apache License 2.0 5 votes vote down vote up
static CredentialsProvider createProxyCredentialsFromSettings(Proxy proxySettings) throws MojoExecutionException {
    if (proxySettings.getUsername() == null) {
        return null;
    }
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(proxySettings.getUsername(), proxySettings.getPassword()));

    return credentialsProvider;
}
 
Example #24
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testUnsignedRequest() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);

    org.opensaml.saml.saml2.core.Response samlResponse =
        parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    webClient.close();
}
 
Example #25
Source File: BasicAuthHttpClientFactory.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public DefaultHttpClient create(final HttpMethod method, final URI uri) {
  final DefaultHttpClient httpclient = super.create(method, uri);

  httpclient.getCredentialsProvider().setCredentials(
          new AuthScope(uri.getHost(), uri.getPort()),
          new UsernamePasswordCredentials(username, password));

  return httpclient;
}
 
Example #26
Source File: HelloWorldWebScriptIT.java    From alfresco-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testWebScriptCall() throws Exception {
    String webscriptURL = getPlatformEndpoint() + "/service/sample/helloworld";
    String expectedResponse = "Message: 'Hello from JS!' 'HelloFromJava'";

    // Login credentials for Alfresco Repo
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "admin");
    provider.setCredentials(AuthScope.ANY, credentials);

    // Create HTTP Client with credentials
    CloseableHttpClient httpclient = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(provider)
            .build();

    // Execute Web Script call
    try {
        HttpGet httpget = new HttpGet(webscriptURL);
        HttpResponse httpResponse = httpclient.execute(httpget);
        assertEquals("Incorrect HTTP Response Status",
                HttpStatus.SC_OK, httpResponse.getStatusLine().getStatusCode());
        HttpEntity entity = httpResponse.getEntity();
        assertNotNull("Response from Web Script is null", entity);
        assertEquals("Incorrect Web Script Response", expectedResponse, EntityUtils.toString(entity));
    } finally {
        httpclient.close();
    }
}
 
Example #27
Source File: AsyncHttpClient.java    From sealtalk-android with MIT License 5 votes vote down vote up
/**
 * Sets the Proxy by it's hostname,port,username and password
 *
 * @param hostname the hostname (IP or DNS name)
 * @param port     the port number. -1 indicates the scheme default port.
 * @param username the username
 * @param password the password
 */
public void setProxy(String hostname, int port, String username, String password) {
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(hostname, port),
            new UsernamePasswordCredentials(username, password));
    final HttpHost proxy = new HttpHost(hostname, port);
    final HttpParams httpParams = this.httpClient.getParams();
    httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
 
Example #28
Source File: AsyncHttpClient.java    From Android-Basics-Codes with Artistic License 2.0 5 votes vote down vote up
/**
 * Sets the Proxy by it's hostname,port,username and password
 *
 * @param hostname the hostname (IP or DNS name)
 * @param port     the port number. -1 indicates the scheme default port.
 * @param username the username
 * @param password the password
 */
public void setProxy(String hostname, int port, String username, String password) {
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(hostname, port),
            new UsernamePasswordCredentials(username, password));
    final HttpHost proxy = new HttpHost(hostname, port);
    final HttpParams httpParams = this.httpClient.getParams();
    httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
 
Example #29
Source File: AsyncHttpClient.java    From MiBandDecompiled with Apache License 2.0 5 votes vote down vote up
public void setBasicAuth(String s, String s1, AuthScope authscope, boolean flag)
{
    UsernamePasswordCredentials usernamepasswordcredentials = new UsernamePasswordCredentials(s, s1);
    CredentialsProvider credentialsprovider = c.getCredentialsProvider();
    if (authscope == null)
    {
        authscope = AuthScope.ANY;
    }
    credentialsprovider.setCredentials(authscope, usernamepasswordcredentials);
    setAuthenticationPreemptive(flag);
}
 
Example #30
Source File: BaseZookeeperURLManager.java    From knox with Apache License 2.0 5 votes vote down vote up
/**
 * Construct an Apache HttpClient with suitable timeout and authentication.
 *
 * @return Apache HttpClient
 */
private CloseableHttpClient buildHttpClient() {
  CloseableHttpClient client;

  // Construct a HttpClient with short term timeout
  RequestConfig.Builder requestBuilder = RequestConfig.custom()
                                                      .setConnectTimeout(TIMEOUT)
                                                      .setSocketTimeout(TIMEOUT)
                                                      .setConnectionRequestTimeout(TIMEOUT);

  // If Kerberos is enabled, allow for challenge/response transparent to client
  if (Boolean.getBoolean(GatewayConfig.HADOOP_KERBEROS_SECURED)) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new NullCredentials());

    Registry<AuthSchemeProvider> authSchemeRegistry =
                          RegistryBuilder.<AuthSchemeProvider>create()
                                         .register(AuthSchemes.SPNEGO, new KnoxSpnegoAuthSchemeFactory(true))
                                         .build();

    client = HttpClientBuilder.create()
                              .setDefaultRequestConfig(requestBuilder.build())
                              .setDefaultAuthSchemeRegistry(authSchemeRegistry)
                              .setDefaultCredentialsProvider(credentialsProvider)
                              .build();
  } else {
    client = HttpClientBuilder.create()
                              .setDefaultRequestConfig(requestBuilder.build())
                              .build();
  }

  return client;
}