Java Code Examples for javax.net.ssl.HttpsURLConnection#setDefaultSSLSocketFactory()

The following examples show how to use javax.net.ssl.HttpsURLConnection#setDefaultSSLSocketFactory() . 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: AbstractSTSTokenTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
static void configureDefaultHttpsConnection() throws GeneralSecurityException, IOException {
    // For localhost testing only
    javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {

        public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
            return "localhost".equals(hostname);
        }
    });

    SSLContext sc = SSLUtils.getSSLContext(TLSClientParametersUtils.getTLSClientParameters());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Needed to prevent test failure using IBM JDK
    if ("IBM Corporation".equals(System.getProperty("java.vendor"))) {
        System.setProperty("https.protocols", "TLSv1");
    }
}
 
Example 2
Source File: NingClientFactory.java    From restcommander with Apache License 2.0 6 votes vote down vote up
private void disableCertificateVerification() throws KeyManagementException, NoSuchAlgorithmException {
	// Create a trust manager that does not validate certificate chains
	final TrustManager[] trustAllCerts = new TrustManager[] { new CustomTrustManager() };

	// Install the all-trusting trust manager
	final SSLContext sslContext = SSLContext.getInstance("SSL");
	sslContext.init(null, trustAllCerts, new SecureRandom());
	final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
	HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
	final HostnameVerifier verifier = new HostnameVerifier() {
		@Override
		public boolean verify(final String hostname, final SSLSession session) {
			return true;
		}
	};

	HttpsURLConnection.setDefaultHostnameVerifier(verifier);
}
 
Example 3
Source File: RestServerEndpointITCase.java    From flink with Apache License 2.0 6 votes vote down vote up
@After
public void teardown() throws Exception {
	if (defaultSSLContext != null) {
		SSLContext.setDefault(defaultSSLContext);
		HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
	}

	if (restClient != null) {
		restClient.shutdown(timeout);
		restClient = null;
	}

	if (serverEndpoint != null) {
		serverEndpoint.closeAsync().get(timeout.getSize(), timeout.getUnit());
		serverEndpoint = null;
	}
}
 
Example 4
Source File: TransportConfigurationTest.java    From msf4j with Apache License 2.0 6 votes vote down vote up
@Override
protected HttpURLConnection request(String path, String method, boolean keepAlive) throws IOException {
    URL url = baseURI.resolve(path).toURL();
    HttpsURLConnection.setDefaultSSLSocketFactory(sslClientContext.getClientContext().getSocketFactory());
    HostnameVerifier allHostsValid = (hostname1, session) -> true;

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    HttpURLConnection urlConn = (HttpsURLConnection) url.openConnection();
    if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT)) {
        urlConn.setDoOutput(true);
    }
    urlConn.setRequestMethod(method);
    if (!keepAlive) {
        urlConn.setRequestProperty(HttpHeaderNames.CONNECTION.toString(), HEADER_VAL_CLOSE);
    }
    return urlConn;
}
 
Example 5
Source File: SSLUtilities.java    From onvif with Apache License 2.0 6 votes vote down vote up
/**
 * Set the default X509 Trust Manager to an instance of a fake class that trust all certificates,
 * even the self-signed ones. This method uses the old deprecated API from the com.sun.ssl
 * package.
 *
 * @deprecated see {@link #_trustAllHttpsCertificates()}.
 */
private static void __trustAllHttpsCertificates() {
  SSLContext context;

  // Create a trust manager that does not validate certificate chains
  if (__trustManagers == null) {
    __trustManagers = new TrustManager[] {new _FakeX509TrustManager()};
  } // if
  // Install the all-trusting trust manager
  try {
    context = SSLContext.getInstance("SSL");
    context.init(null, __trustManagers, new SecureRandom());
  } catch (GeneralSecurityException gse) {
    throw new IllegalStateException(gse.getMessage());
  } // catch
  HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
}
 
Example 6
Source File: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
protected static void startServer(String servletContextName, String fedizConfigPath) throws Exception {
    assertNotNull("Property 'idp.https.port' null", IDP_HTTPS_PORT);
    assertNotNull("Property 'rp.https.port' null", RP_HTTPS_PORT);

    idpServer = startServer(IDP_HTTPS_PORT, null, null);
    rpServer = startServer(RP_HTTPS_PORT, servletContextName, fedizConfigPath);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    try (InputStream is = Loader.getResource("/server.jks").openStream()) {
        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(is, "tompass".toCharArray());
        tmf.init(keyStore);
    }
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, tmf.getTrustManagers(), new java.security.SecureRandom()); 
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    loginToClientsPage(servletContextName);
}
 
Example 7
Source File: GeoServerRestClient.java    From geowave with Apache License 2.0 5 votes vote down vote up
private WebTarget getWebTarget() {
  if (webTarget == null) {
    String url = getConfig().getUrl();
    if (url != null) {
      url = url.trim().toLowerCase(Locale.ROOT);
      Client client = null;
      if (url.startsWith("http://")) {
        client = ClientBuilder.newClient();
      } else if (url.startsWith("https://")) {
        final SslConfigurator sslConfig = SslConfigurator.newInstance();
        if (getConfig().getGsConfigProperties() != null) {
          loadSSLConfigurations(sslConfig, getConfig().getGsConfigProperties());
        }
        final SSLContext sslContext = sslConfig.createSSLContext();

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        client = ClientBuilder.newBuilder().sslContext(sslContext).build();
      }
      if (client != null) {
        client.register(
            HttpAuthenticationFeature.basic(getConfig().getUser(), getConfig().getPass()));
        try {
          webTarget = client.target(new URI(url));
        } catch (final URISyntaxException e) {
          LOGGER.error("Unable to parse geoserver URL: " + url, e);
        }
      }
    }
  }

  return webTarget;
}
 
Example 8
Source File: WebServiceTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private String makeHttpRequest(boolean useTls, boolean useAuth) throws Exception {
    InputStream response = null;
    try {
        if (useTls) {
            KeyManager[] keyManagers = null;
            if (useAuth) {
                Certificate[] tlsCert = SecurityUtility.loadCertificatesFromPemFile(TLS_CLIENT_CERT_FILE_PATH);
                PrivateKey tlsKey = SecurityUtility.loadPrivateKeyFromPemFile(TLS_CLIENT_KEY_FILE_PATH);

                KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
                ks.load(null, null);
                ks.setKeyEntry("private", tlsKey, "".toCharArray(), tlsCert);

                KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                kmf.init(ks, "".toCharArray());
                keyManagers = kmf.getKeyManagers();
            }
            TrustManager[] trustManagers = InsecureTrustManagerFactory.INSTANCE.getTrustManagers();
            SSLContext sslCtx = SSLContext.getInstance("TLS");
            sslCtx.init(keyManagers, trustManagers, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory());
            response = new URL(BROKER_LOOKUP_URL_TLS).openStream();
        } else {
            response = new URL(BROKER_LOOKUP_URL).openStream();
        }
        String resp = CharStreams.toString(new InputStreamReader(response));
        log.info("Response: {}", resp);
        return resp;
    } finally {
        Closeables.close(response, false);
    }
}
 
Example 9
Source File: DockerElasticSearch.java    From james-project with Apache License 2.0 5 votes vote down vote up
public Builder disableSSLValidation() throws Exception {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, TRUST_ALL, new java.security.SecureRandom());
    SSLSocketFactory factory = sc.getSocketFactory();
    HttpsURLConnection.setDefaultSSLSocketFactory(factory);
    Client ignoredSSLClient = new Client.Default(factory, ACCEPT_ANY_HOST);

    requestBuilder.client(ignoredSSLClient);

    return this;
}
 
Example 10
Source File: LianlianSslUtils.java    From aaden-pay with Apache License 2.0 5 votes vote down vote up
private static void trustAllHttpsCertificates() throws Exception {
	TrustManager[] trustAllCerts = new TrustManager[1];
	TrustManager tm = new miTM();
	trustAllCerts[0] = tm;
	SSLContext sc = SSLContext.getInstance("SSL");
	sc.init(null, trustAllCerts, null);
	HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
 
Example 11
Source File: SessionTest.java    From openerp-java-api with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startProxy() throws Exception {
	if (isUsingMockServer()) {
		previousFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
		HttpsURLConnection.setDefaultSSLSocketFactory(SSLFactory.getInstance().sslContext().getSocketFactory());
		proxy = ClientAndProxy.startClientAndProxy(PortFactory.findFreePort());
		mockServer = ClientAndServer.startClientAndServer(MOCKSERVER_PORT);
	}
}
 
Example 12
Source File: SessionAuthenticationServiceTest.java    From okta-sdk-appauth-android with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    mAuthStateManager = AuthStateManager.getInstance(RuntimeEnvironment.application);

    MockWebServer server = new MockWebServer();
    dispatcher = new CustomDispatcher();
    server.setDispatcher(dispatcher);

    SSLSocketFactory sslSocketFactory = TestUtils.getSSL(this);
    HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });
    server.useHttps(sslSocketFactory, false);
    server.start();
    String baseUrl = server.url("/").toString();
    authorizationRequest = TestUtils.getMinimalAuthRequestBuilder(baseUrl, ResponseTypeValues.CODE);

    mAuthService = new AuthorizationService(RuntimeEnvironment.application.getApplicationContext(), new AppAuthConfiguration.Builder().setConnectionBuilder(ConnectionBuilderForTest.INSTANCE).build());

    sessionAuthenticationService = new SessionAuthenticationService(mAuthStateManager, mAuthService, new ConnectionBuilder() {
        @NonNull
        @Override
        public HttpURLConnection openConnection(@NonNull Uri uri) throws IOException {
            return DefaultOktaConnectionBuilder.INSTANCE.openConnection(uri);
        }
    });

    request = authorizationRequest.build();
    dispatcher.nonce = request.nonce;
}
 
Example 13
Source File: SslUtils.java    From lemon with Apache License 2.0 5 votes vote down vote up
private static void trustAllHttpsCertificates() throws Exception {
    TrustManager[] trustAllCerts = new TrustManager[1];
    trustAllCerts[0] = new MockTrustManager();

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
 
Example 14
Source File: ConfigurationModuleSSLVerifier.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public void unload() throws TechnicalConnectorException {
   LOG.debug("Unloading ConfigurationModule " + this.getClass().getName());
   HttpsURLConnection.setDefaultSSLSocketFactory(this.oldSSLSocketFactory);
}
 
Example 15
Source File: ApigeeHttpsURLConnection.java    From apigee-android-sdk with Apache License 2.0 4 votes vote down vote up
public static void setDefaultSSLSocketFactory(SSLSocketFactory sf)
{
	HttpsURLConnection.setDefaultSSLSocketFactory(sf);
}
 
Example 16
Source File: MySSLSocketFactory.java    From Mobike with Apache License 2.0 4 votes vote down vote up
/**
 * Makes HttpsURLConnection trusts getUrl set of certificates specified by the KeyStore
 */
public void fixHttpsURLConnection() {
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
}
 
Example 17
Source File: BrokerServiceLookupTest.java    From pulsar with Apache License 2.0 4 votes vote down vote up
/**
 * 1. Start broker1 and broker2 with tls enable 2. Hit HTTPS lookup url at broker2 which redirects to HTTPS broker1
 *
 * @throws Exception
 */
@Test
public void testWebserviceServiceTls() throws Exception {
    log.info("-- Starting {} test --", methodName);
    final String TLS_SERVER_CERT_FILE_PATH = "./src/test/resources/certificate/server.crt";
    final String TLS_SERVER_KEY_FILE_PATH = "./src/test/resources/certificate/server.key";
    final String TLS_CLIENT_CERT_FILE_PATH = "./src/test/resources/certificate/client.crt";
    final String TLS_CLIENT_KEY_FILE_PATH = "./src/test/resources/certificate/client.key";

    /**** start broker-2 ****/
    ServiceConfiguration conf2 = new ServiceConfiguration();
    conf2.setAdvertisedAddress("localhost");
    conf2.setBrokerServicePort(Optional.of(0));
    conf2.setBrokerServicePortTls(Optional.of(0));
    conf2.setWebServicePort(Optional.of(0));
    conf2.setWebServicePortTls(Optional.of(0));
    conf2.setAdvertisedAddress("localhost");
    conf2.setTlsAllowInsecureConnection(true);
    conf2.setTlsCertificateFilePath(TLS_SERVER_CERT_FILE_PATH);
    conf2.setTlsKeyFilePath(TLS_SERVER_KEY_FILE_PATH);
    conf2.setClusterName(conf.getClusterName());
    conf2.setZookeeperServers("localhost:2181");

    @Cleanup
    PulsarService pulsar2 = startBroker(conf2);

    // restart broker1 with tls enabled
    conf.setBrokerServicePortTls(Optional.of(0));
    conf.setWebServicePortTls(Optional.of(0));
    conf.setTlsAllowInsecureConnection(true);
    conf.setTlsCertificateFilePath(TLS_SERVER_CERT_FILE_PATH);
    conf.setTlsKeyFilePath(TLS_SERVER_KEY_FILE_PATH);
    stopBroker();
    startBroker();
    pulsar.getLoadManager().get().writeLoadReportOnZookeeper();
    pulsar2.getLoadManager().get().writeLoadReportOnZookeeper();

    LoadManager loadManager1 = spy(pulsar.getLoadManager().get());
    LoadManager loadManager2 = spy(pulsar2.getLoadManager().get());
    Field loadManagerField = NamespaceService.class.getDeclaredField("loadManager");
    loadManagerField.setAccessible(true);

    // mock: redirect request to leader [2]
    doReturn(true).when(loadManager2).isCentralized();
    loadManagerField.set(pulsar2.getNamespaceService(), new AtomicReference<>(loadManager2));
    loadManagerField.set(pulsar.getNamespaceService(), new AtomicReference<>(loadManager1));

    // mock: return Broker2 as a Least-loaded broker when leader receives
    // request [3]
    doReturn(true).when(loadManager1).isCentralized();
    doReturn(true).when(loadManager2).isCentralized();
    SimpleResourceUnit resourceUnit = new SimpleResourceUnit(pulsar.getWebServiceAddress(), null);
    doReturn(Optional.of(resourceUnit)).when(loadManager2).getLeastLoaded(any(ServiceUnitId.class));
    doReturn(Optional.of(resourceUnit)).when(loadManager1).getLeastLoaded(any(ServiceUnitId.class));


    /**** started broker-2 ****/

    URI brokerServiceUrl = new URI("pulsar://localhost:" + conf2.getBrokerServicePort().get());
    @Cleanup
    PulsarClient pulsarClient2 = PulsarClient.builder().serviceUrl(brokerServiceUrl.toString()).build();

    final String lookupResourceUrl = "/lookup/v2/topic/persistent/my-property/my-ns/my-topic1";

    // set client cert_key file
    KeyManager[] keyManagers = null;
    Certificate[] tlsCert = SecurityUtility.loadCertificatesFromPemFile(TLS_CLIENT_CERT_FILE_PATH);
    PrivateKey tlsKey = SecurityUtility.loadPrivateKeyFromPemFile(TLS_CLIENT_KEY_FILE_PATH);
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null, null);
    ks.setKeyEntry("private", tlsKey, "".toCharArray(), tlsCert);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, "".toCharArray());
    keyManagers = kmf.getKeyManagers();
    TrustManager[] trustManagers = InsecureTrustManagerFactory.INSTANCE.getTrustManagers();
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(keyManagers, trustManagers, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory());

    // hit broker2 url
    URLConnection con = new URL(pulsar2.getWebServiceAddressTls() + lookupResourceUrl).openConnection();
    log.info("orignal url: {}", con.getURL());
    con.connect();
    log.info("connected url: {} ", con.getURL());
    // assert connect-url: broker2-https
    assertEquals(new Integer(con.getURL().getPort()), conf2.getWebServicePortTls().get());
    InputStream is = con.getInputStream();
    // assert redirect-url: broker1-https only
    log.info("redirected url: {}", con.getURL());
    assertEquals(new Integer(con.getURL().getPort()), conf.getWebServicePortTls().get());
    is.close();

    loadManager1 = null;
    loadManager2 = null;
}
 
Example 18
Source File: MySSLSocketFactory.java    From MiBandDecompiled with Apache License 2.0 4 votes vote down vote up
public void fixHttpsURLConnection()
{
    HttpsURLConnection.setDefaultSSLSocketFactory(a.getSocketFactory());
}
 
Example 19
Source File: UrlConnectionHttpClientWireMockTest.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
@After
public void reset() {
    HttpsURLConnection.setDefaultSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
}
 
Example 20
Source File: RestServerEndpointITCase.java    From flink with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() throws Exception {
	config.setString(WebOptions.UPLOAD_DIR, temporaryFolder.newFolder().getCanonicalPath());

	defaultSSLContext = SSLContext.getDefault();
	defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
	final SSLContext sslClientContext = SSLUtils.createRestSSLContext(config, true);
	if (sslClientContext != null) {
		SSLContext.setDefault(sslClientContext);
		HttpsURLConnection.setDefaultSSLSocketFactory(sslClientContext.getSocketFactory());
	}

	RestServerEndpointConfiguration serverConfig = RestServerEndpointConfiguration.fromConfiguration(config);
	RestClientConfiguration clientConfig = RestClientConfiguration.fromConfiguration(config);

	RestfulGateway mockRestfulGateway = mock(RestfulGateway.class);

	final GatewayRetriever<RestfulGateway> mockGatewayRetriever = () ->
		CompletableFuture.completedFuture(mockRestfulGateway);

	testHandler = new TestHandler(
		mockGatewayRetriever,
		RpcUtils.INF_TIMEOUT);

	TestVersionHandler testVersionHandler = new TestVersionHandler(
		mockGatewayRetriever,
		RpcUtils.INF_TIMEOUT);

	TestVersionSelectionHandler1 testVersionSelectionHandler1 = new TestVersionSelectionHandler1(
		mockGatewayRetriever,
		RpcUtils.INF_TIMEOUT);

	TestVersionSelectionHandler2 testVersionSelectionHandler2 = new TestVersionSelectionHandler2(
		mockGatewayRetriever,
		RpcUtils.INF_TIMEOUT);

	testUploadHandler = new TestUploadHandler(
		mockGatewayRetriever,
		RpcUtils.INF_TIMEOUT);

	final StaticFileServerHandler<RestfulGateway> staticFileServerHandler = new StaticFileServerHandler<>(
		mockGatewayRetriever,
		RpcUtils.INF_TIMEOUT,
		temporaryFolder.getRoot());

	final List<Tuple2<RestHandlerSpecification, ChannelInboundHandler>> handlers = Arrays.asList(
		Tuple2.of(new TestHeaders(), testHandler),
		Tuple2.of(TestUploadHeaders.INSTANCE, testUploadHandler),
		Tuple2.of(testVersionHandler.getMessageHeaders(), testVersionHandler),
		Tuple2.of(testVersionSelectionHandler1.getMessageHeaders(), testVersionSelectionHandler1),
		Tuple2.of(testVersionSelectionHandler2.getMessageHeaders(), testVersionSelectionHandler2),
		Tuple2.of(WebContentHandlerSpecification.getInstance(), staticFileServerHandler));

	serverEndpoint = new TestRestServerEndpoint(serverConfig, handlers);
	restClient = new TestRestClient(clientConfig);

	serverEndpoint.start();
	serverAddress = serverEndpoint.getServerAddress();
}