Java Code Examples for javax.net.ssl.HostnameVerifier

The following are top voted examples for showing how to use javax.net.ssl.HostnameVerifier. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: RoughWorld   File: WebClient.java   View source code 8 votes vote down vote up
public static void disableCertificateValidation() 
{
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] 
    { 
      new TrustAllManager() 
    };

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new TrustAllHostnameVerifier();
    
    // Install the all-trusting trust manager
    try 
    {
      SSLContext sc = SSLContext.getInstance("SSL");
      sc.init(null, trustAllCerts, new SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {}
}
 
Example 2
Project: calcite-avatica   File: AvaticaCommonsHttpClientImpl.java   View source code 7 votes vote down vote up
/**
 * Creates the {@code HostnameVerifier} given the provided {@code verification}.
 *
 * @param verification The intended hostname verification action.
 * @return A verifier for the request verification.
 * @throws IllegalArgumentException if the provided verification cannot be handled.
 */
HostnameVerifier getHostnameVerifier(HostnameVerification verification) {
  // Normally, the configuration logic would give us a default of STRICT if it was not
  // provided by the user. It's easy for us to do a double-check.
  if (verification == null) {
    verification = HostnameVerification.STRICT;
  }
  switch (verification) {
  case STRICT:
    return SSLConnectionSocketFactory.getDefaultHostnameVerifier();
  case NONE:
    return NoopHostnameVerifier.INSTANCE;
  default:
    throw new IllegalArgumentException("Unhandled HostnameVerification: "
        + hostnameVerification);
  }
}
 
Example 3
Project: GitHub   File: Address.java   View source code 7 votes vote down vote up
public Address(String uriHost, int uriPort, Dns dns, SocketFactory socketFactory,
    @Nullable SSLSocketFactory sslSocketFactory, @Nullable HostnameVerifier hostnameVerifier,
    @Nullable CertificatePinner certificatePinner, Authenticator proxyAuthenticator,
    @Nullable Proxy proxy, List<Protocol> protocols, List<ConnectionSpec> connectionSpecs,
    ProxySelector proxySelector) {
  this.url = new HttpUrl.Builder()
      .scheme(sslSocketFactory != null ? "https" : "http")
      .host(uriHost)
      .port(uriPort)
      .build();

  if (dns == null) throw new NullPointerException("dns == null");
  this.dns = dns;

  if (socketFactory == null) throw new NullPointerException("socketFactory == null");
  this.socketFactory = socketFactory;

  if (proxyAuthenticator == null) {
    throw new NullPointerException("proxyAuthenticator == null");
  }
  this.proxyAuthenticator = proxyAuthenticator;

  if (protocols == null) throw new NullPointerException("protocols == null");
  this.protocols = Util.immutableList(protocols);

  if (connectionSpecs == null) throw new NullPointerException("connectionSpecs == null");
  this.connectionSpecs = Util.immutableList(connectionSpecs);

  if (proxySelector == null) throw new NullPointerException("proxySelector == null");
  this.proxySelector = proxySelector;

  this.proxy = proxy;
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
  this.certificatePinner = certificatePinner;
}
 
Example 4
Project: AndroidModulePattern   File: HttpsUtils.java   View source code 7 votes vote down vote up
/**
 * 主机名校验方法,请把”192.168.0.10”换成你们公司的主机IP:
 */
public static HostnameVerifier getHostnameVerifier() {
    return new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            if ("192.168.0.10".equals(hostname)) {
                return true;
            } else {
                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
                return hv.verify(hostname, session);
            }
        }
    };
}
 
Example 5
Project: boohee_v5.6   File: HttpsTrustManager.java   View source code 6 votes vote down vote up
public static void allowAllSSL() {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    });
    SSLContext context = null;
    if (trustManagers == null) {
        trustManagers = new TrustManager[]{new HttpsTrustManager()};
    }
    try {
        context = SSLContext.getInstance("TLS");
        context.init(null, trustManagers, new SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e2) {
        e2.printStackTrace();
    }
    HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
}
 
Example 6
Project: GitHub   File: OkHttp.java   View source code 6 votes vote down vote up
@Override public void prepare(Benchmark benchmark) {
  super.prepare(benchmark);
  client = new OkHttpClient.Builder()
      .protocols(benchmark.protocols)
      .build();

  if (benchmark.tls) {
    SslClient sslClient = SslClient.localhost();
    SSLSocketFactory socketFactory = sslClient.socketFactory;
    HostnameVerifier hostnameVerifier = new HostnameVerifier() {
      @Override public boolean verify(String s, SSLSession session) {
        return true;
      }
    };
    client = new OkHttpClient.Builder()
        .sslSocketFactory(socketFactory, sslClient.trustManager)
        .hostnameVerifier(hostnameVerifier)
        .build();
  }
}
 
Example 7
Project: hadoop-oss   File: SSLFactory.java   View source code 6 votes vote down vote up
public static HostnameVerifier getHostnameVerifier(String verifier)
  throws GeneralSecurityException, IOException {
  HostnameVerifier hostnameVerifier;
  if (verifier.equals("DEFAULT")) {
    hostnameVerifier = SSLHostnameVerifier.DEFAULT;
  } else if (verifier.equals("DEFAULT_AND_LOCALHOST")) {
    hostnameVerifier = SSLHostnameVerifier.DEFAULT_AND_LOCALHOST;
  } else if (verifier.equals("STRICT")) {
    hostnameVerifier = SSLHostnameVerifier.STRICT;
  } else if (verifier.equals("STRICT_IE6")) {
    hostnameVerifier = SSLHostnameVerifier.STRICT_IE6;
  } else if (verifier.equals("ALLOW_ALL")) {
    hostnameVerifier = SSLHostnameVerifier.ALLOW_ALL;
  } else {
    throw new GeneralSecurityException("Invalid hostname verifier: " +
                                       verifier);
  }
  return hostnameVerifier;
}
 
Example 8
Project: yyox   File: OkHttpManager.java   View source code 6 votes vote down vote up
public static OkHttpManager getInstance() {
    if (sOkHttpManager == null) {
        synchronized (OkHttpManager.class) {
            if (sOkHttpManager == null) {
                sOkHttpManager = new OkHttpManager();
                sOkHttpClient = new OkHttpClient.Builder()
                        .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                        .connectTimeout(20, TimeUnit.SECONDS)
                        .readTimeout(20, TimeUnit.SECONDS)
                        .writeTimeout(20, TimeUnit.SECONDS)
                        .retryOnConnectionFailure(true)
                        .addNetworkInterceptor(new HttpInterceptor(SPUtils.getUserAgent()))
                        .hostnameVerifier(new HostnameVerifier() {
                            @Override
                            public boolean verify(String hostname, SSLSession session) {
                                return true;
                            }
                        })
                        .sslSocketFactory(TrustSSLContext.getSSLSocketFactory())

                        .build();
            }
        }
    }
    return sOkHttpManager;
}
 
Example 9
Project: JRediClients   File: JedisFactory.java   View source code 6 votes vote down vote up
public JedisFactory(final URI uri, final int connectionTimeout, final int soTimeout, final String clientName,
		final boolean ssl, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
		final HostnameVerifier hostnameVerifier) {
	if (!JedisURIHelper.isValid(uri)) {
		throw new InvalidURIException(
				String.format("Cannot open Redis connection due invalid URI. %s", uri.toString()));
	}

	this.hostAndPort.set(new HostAndPort(uri.getHost(), uri.getPort()));
	this.connectionTimeout = connectionTimeout;
	this.soTimeout = soTimeout;
	this.password = JedisURIHelper.getPassword(uri);
	this.database = JedisURIHelper.getDBIndex(uri);
	this.clientName = clientName;
	this.ssl = ssl;
	this.sslSocketFactory = sslSocketFactory;
	this.sslParameters = sslParameters;
	this.hostnameVerifier = hostnameVerifier;
}
 
Example 10
Project: calcite-avatica   File: AvaticaCommonsHttpClientImplTest.java   View source code 6 votes vote down vote up
@Test public void testHostnameVerification() throws Exception {
  AvaticaCommonsHttpClientImpl client = mock(AvaticaCommonsHttpClientImpl.class);
  // Call the real method
  when(client.getHostnameVerifier(nullable(HostnameVerification.class)))
      .thenCallRealMethod();

  // No verification should give the default (strict) verifier
  HostnameVerifier actualVerifier = client.getHostnameVerifier(null);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof DefaultHostnameVerifier);

  actualVerifier = client.getHostnameVerifier(HostnameVerification.STRICT);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof DefaultHostnameVerifier);

  actualVerifier = client.getHostnameVerifier(HostnameVerification.NONE);
  assertNotNull(actualVerifier);
  assertTrue(actualVerifier instanceof NoopHostnameVerifier);
}
 
Example 11
Project: ITSM   File: GlideUtils.java   View source code 6 votes vote down vote up
public static synchronized OkHttpClient getOkHttpClient() {
  if (okHttpClient == null) {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.connectTimeout(90, TimeUnit.SECONDS);
    builder.sslSocketFactory(createSSLSocketFactory());
    builder.hostnameVerifier(new HostnameVerifier() {
      @Override public boolean verify(String hostname, SSLSession session) {
        return true;
      }
    });
    if (BuildConfig.DEBUG) {
      // Log信息拦截器
      HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
      loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);//这里可以选择拦截级别

      //设置 Debug Log 模式
      builder.addInterceptor(loggingInterceptor);
    }
    okHttpClient = builder.build();
  }
  return okHttpClient;
}
 
Example 12
Project: JRediClients   File: JedisClusterInfoCache.java   View source code 6 votes vote down vote up
public JedisPool setupNodeIfNotExist(HostAndPort node, boolean ssl, SSLSocketFactory sslSocketFactory,
		SSLParameters sslParameters, HostnameVerifier hostnameVerifier) {
	w.lock();
	try {
		String nodeKey = getNodeKey(node);
		JedisPool existingPool = nodes.get(nodeKey);
		if (existingPool != null)
			return existingPool;

		JedisPool nodePool = new JedisPool(poolConfig, node.getHost(), node.getPort(), connectionTimeout, soTimeout,
				password, 0, null, ssl, sslSocketFactory, sslParameters, hostnameVerifier);
		nodes.put(nodeKey, nodePool);
		return nodePool;
	} finally {
		w.unlock();
	}
}
 
Example 13
Project: JRediClients   File: SSLJedisTest.java   View source code 6 votes vote down vote up
/**
 * Tests opening an SSL/TLS connection to redis with a custom hostname
 * verifier.
 */
@Test
public void connectWithShardInfoAndCustomHostnameVerifier() {
  final URI uri = URI.create("rediss://localhost:6390");
  final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
  final SSLParameters sslParameters = new SSLParameters();

  HostnameVerifier hostnameVerifier = new BasicHostnameVerifier();
  JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, hostnameVerifier);
  shardInfo.setPassword("foobared");

  Jedis jedis = new Jedis(shardInfo);
  jedis.get("foo");
  jedis.disconnect();
  jedis.close();
}
 
Example 14
Project: alexa-gira-bridge   File: Util.java   View source code 6 votes vote down vote up
public static String triggerHttpGetWithCustomSSL(String requestUrl) {
	String result = null;
	try {
		SSLContextBuilder builder = new SSLContextBuilder();
		builder.loadTrustMaterial(null, new TrustSelfSignedStrategy() {
			public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
				return true;
			}
		});
		@SuppressWarnings("deprecation")
		HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), hostnameVerifier);

		CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

		HttpGet httpGet = new HttpGet("https://" + requestUrl);
		CloseableHttpResponse response = httpclient.execute(httpGet);
		try {
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity);
				log.debug("Received response: " + result);
			} else {
				log.error("Request not successful. StatusCode was " + response.getStatusLine().getStatusCode());
			}
		} finally {
			response.close();
		}
	} catch (IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
		log.error("Error executing the request.", e);
	}
	return result;
}
 
Example 15
Project: JRediClients   File: SSLJedisTest.java   View source code 6 votes vote down vote up
/**
 * Tests opening an SSL/TLS connection to redis with a custom hostname
 * verifier. This test should fail because "127.0.0.1" does not match the
 * certificate subject common name and there are no subject alternative names
 * in the certificate.
 */
@Test
public void connectWithShardInfoAndCustomHostnameVerifierByIpAddress() {
  final URI uri = URI.create("rediss://127.0.0.1:6390");
  final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
  final SSLParameters sslParameters = new SSLParameters();

  HostnameVerifier hostnameVerifier = new BasicHostnameVerifier();
  JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, hostnameVerifier);
  shardInfo.setPassword("foobared");

  Jedis jedis = new Jedis(shardInfo);
  try {
    jedis.get("foo");
    Assert.fail("The code did not throw the expected JedisConnectionException.");
  } catch (JedisConnectionException e) {
    Assert.assertEquals("The JedisConnectionException does not contain the expected message.",
        "The connection to '127.0.0.1' failed ssl/tls hostname verification.", e.getMessage());
  }

  try {
    jedis.close();
  } catch (Throwable e1) {
    // Expected.
  }
}
 
Example 16
Project: aliyun-cloudphotos-android-demo   File: SSLUtil.java   View source code 5 votes vote down vote up
/**
 * 忽略HTTPS请求的SSL证书,必须在openConnection之前调用
 * @throws Exception
 */
public static void ignoreSsl() throws Exception{
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }
    };
    trustAllHttpsCertificates();
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
 
Example 17
Project: LoRaWAN-Smart-Parking   File: HttpEngine.java   View source code 5 votes vote down vote up
/** Connect to the origin server either directly or via a proxy. */
protected final void connect() throws IOException {
  if (connection != null) {
    return;
  }
  if (routeSelector == null) {
    String uriHost = uri.getHost();
    if (uriHost == null) {
      throw new UnknownHostException(uri.toString());
    }
    SSLSocketFactory sslSocketFactory = null;
    HostnameVerifier hostnameVerifier = null;
    if (uri.getScheme().equalsIgnoreCase("https")) {
      sslSocketFactory = client.getSslSocketFactory();
      hostnameVerifier = client.getHostnameVerifier();
    }
    Address address = new Address(uriHost, getEffectivePort(uri), sslSocketFactory,
        hostnameVerifier, client.getAuthenticator(), client.getProxy(), client.getTransports());
    routeSelector = new RouteSelector(address, uri, client.getProxySelector(),
        client.getConnectionPool(), Dns.DEFAULT, client.getRoutesDatabase());
  }
  connection = routeSelector.next(method);
  if (!connection.isConnected()) {
    connection.connect(client.getConnectTimeout(), client.getReadTimeout(), getTunnelConfig());
    client.getConnectionPool().maybeShare(connection);
    client.getRoutesDatabase().connected(connection.getRoute());
  } else if (!connection.isSpdy()) {
      connection.updateReadTimeout(client.getReadTimeout());
  }
  connected(connection);
  if (connection.getRoute().getProxy() != client.getProxy()) {
    // Update the request line if the proxy changed; it may need a host name.
    requestHeaders.getHeaders().setRequestLine(getRequestLine());
  }
}
 
Example 18
Project: aws-sdk-java-v2   File: SdkTlsSocketFactory.java   View source code 5 votes vote down vote up
public SdkTlsSocketFactory(final SSLContext sslContext, final HostnameVerifier hostnameVerifier) {
    super(sslContext, hostnameVerifier);
    if (sslContext == null) {
        throw new IllegalArgumentException(
                "sslContext must not be null. " + "Use SSLContext.getDefault() if you are unsure.");
    }
    this.sslContext = sslContext;
}
 
Example 19
Project: boohee_v5.6   File: Address.java   View source code 5 votes vote down vote up
public Address(String uriHost, int uriPort, Dns dns, SocketFactory socketFactory,
               SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier,
               CertificatePinner certificatePinner, Authenticator authenticator, Proxy proxy,
               List<Protocol> protocols, List<ConnectionSpec> connectionSpecs, ProxySelector
                       proxySelector) {
    this.url = new Builder().scheme(sslSocketFactory != null ? b.a : "http").host(uriHost)
            .port(uriPort).build();
    if (dns == null) {
        throw new IllegalArgumentException("dns == null");
    }
    this.dns = dns;
    if (socketFactory == null) {
        throw new IllegalArgumentException("socketFactory == null");
    }
    this.socketFactory = socketFactory;
    if (authenticator == null) {
        throw new IllegalArgumentException("authenticator == null");
    }
    this.authenticator = authenticator;
    if (protocols == null) {
        throw new IllegalArgumentException("protocols == null");
    }
    this.protocols = Util.immutableList((List) protocols);
    if (connectionSpecs == null) {
        throw new IllegalArgumentException("connectionSpecs == null");
    }
    this.connectionSpecs = Util.immutableList((List) connectionSpecs);
    if (proxySelector == null) {
        throw new IllegalArgumentException("proxySelector == null");
    }
    this.proxySelector = proxySelector;
    this.proxy = proxy;
    this.sslSocketFactory = sslSocketFactory;
    this.hostnameVerifier = hostnameVerifier;
    this.certificatePinner = certificatePinner;
}
 
Example 20
Project: fort_w   File: Web.java   View source code 5 votes vote down vote up
/**
 * @see http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/
 * @return
 * @throws Exception
 */
public static synchronized HttpClient getHttpClient() throws Exception
{
   HttpClientBuilder b = HttpClientBuilder.create();

   // setup a Trust Strategy that allows all certificates.
   //
   SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy()
      {
         public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
         {
            return true;
         }
      }).build();
   b.setSslcontext(sslContext);

   // don't check Hostnames, either.
   //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
   HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

   // here's the special part:
   //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
   //      -- and create a Registry, to register it.
   //
   SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
   //Registry<ConnectionSocketFactory> socketFactoryRegistry = ;

   // now, we create connection-manager using our Registry.
   //      -- allows multi-threaded use
   PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build());
   b.setConnectionManager(connMgr);

   // finally, build the HttpClient;
   //      -- done!
   HttpClient client = b.build();

   return client;
}
 
Example 21
Project: GitHub   File: Main.java   View source code 5 votes vote down vote up
private static HostnameVerifier createInsecureHostnameVerifier() {
  return new HostnameVerifier() {
    @Override public boolean verify(String s, SSLSession sslSession) {
      return true;
    }
  };
}
 
Example 22
Project: af-pay   File: HttpsUtils.java   View source code 5 votes vote down vote up
@Override
public boolean verify(String hostname, SSLSession session) {
    System.out.println("verify " + hostname);
    HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
    return hv.verify(hostname, session);
}
 
Example 23
Project: GitHub   File: UrlConnection.java   View source code 5 votes vote down vote up
@Override public void prepare(Benchmark benchmark) {
  super.prepare(benchmark);
  if (benchmark.tls) {
    SslClient sslClient = SslClient.localhost();
    SSLSocketFactory socketFactory = sslClient.socketFactory;
    HostnameVerifier hostnameVerifier = new HostnameVerifier() {
      @Override public boolean verify(String s, SSLSession session) {
        return true;
      }
    };
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
    HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
  }
}
 
Example 24
Project: cas4.0.x-server-wechat   File: SimpleHttpClientTests.java   View source code 5 votes vote down vote up
private HostnameVerifier getFriendlyToAllHostnameVerifier() {
    final HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(final String hostname, final SSLSession session) { return true; }
    };
    return hv;
}
 
Example 25
Project: StubbornJava   File: HttpClient.java   View source code 5 votes vote down vote up
public static OkHttpClient trustAllSslClient(OkHttpClient client) {
    log.warn("Using the trustAllSslClient is highly discouraged and should not be used in Production!");
    Builder builder = client.newBuilder();
    builder.sslSocketFactory(trustAllSslSocketFactory, (X509TrustManager)trustAllCerts[0]);
    builder.hostnameVerifier(new HostnameVerifier() {
      @Override
      public boolean verify(String hostname, SSLSession session) {
        return true;
      }
    });
    return builder.build();
}
 
Example 26
Project: CrawlerSYS   File: WebCrawler.java   View source code 5 votes vote down vote up
/**
 * 忽略HTTPS请求的SSL证书,必须在openConnection之前调用
 * @throws Exception
 */
public static void ignoreSsl() throws Exception{
	HostnameVerifier hv = new HostnameVerifier() {
		@Override
		public boolean verify(String urlHostName, SSLSession session) {
			System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
			logger.info("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
			return true;
		}
	};
	trustAllHttpsCertificates();
	HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
 
Example 27
Project: Mastering-Java-EE-Development-with-WildFly   File: RestTestCase.java   View source code 5 votes vote down vote up
@Test
public void testSSLContext() throws Exception {
	logger.info("start SSL Context test");
	Client client = newClient();
	HostnameVerifier hostnameVerifier = client.getHostnameVerifier();
	assertNotNull("Java Utility", hostnameVerifier);
	assertNull("no SSL by default", client.getSslContext());
}
 
Example 28
Project: cas-5.1.0   File: SSOPostProfileCallbackHandlerController.java   View source code 5 votes vote down vote up
/**
 * Instantiates a new idp-sso post saml profile handler controller.
 *
 * @param samlObjectSigner                             the saml object signer
 * @param parserPool                                   the parser pool
 * @param authenticationSystemSupport                  the authentication system support
 * @param servicesManager                              the services manager
 * @param webApplicationServiceFactory                 the web application service factory
 * @param samlRegisteredServiceCachingMetadataResolver the saml registered service caching metadata resolver
 * @param configBean                                   the config bean
 * @param responseBuilder                              the response builder
 * @param authenticationContextClassMappings           the authentication context class mappings
 * @param serverPrefix                                 the server prefix
 * @param serverName                                   the server name
 * @param authenticationContextRequestParameter        the authentication context request parameter
 * @param loginUrl                                     the login url
 * @param logoutUrl                                    the logout url
 * @param forceSignedLogoutRequests                    the force signed logout requests
 * @param singleLogoutCallbacksDisabled                the single logout callbacks disabled
 * @param samlObjectSignatureValidator                 the saml object signature validator
 */
public SSOPostProfileCallbackHandlerController(final BaseSamlObjectSigner samlObjectSigner,
                                               final ParserPool parserPool,
                                               final AuthenticationSystemSupport authenticationSystemSupport,
                                               final ServicesManager servicesManager,
                                               final ServiceFactory<WebApplicationService> webApplicationServiceFactory,
                                               final SamlRegisteredServiceCachingMetadataResolver samlRegisteredServiceCachingMetadataResolver,
                                               final OpenSamlConfigBean configBean,
                                               final SamlProfileObjectBuilder<Response> responseBuilder,
                                               final Set<String> authenticationContextClassMappings,
                                               final String serverPrefix,
                                               final String serverName,
                                               final String authenticationContextRequestParameter,
                                               final String loginUrl,
                                               final String logoutUrl,
                                               final boolean forceSignedLogoutRequests,
                                               final boolean singleLogoutCallbacksDisabled,
                                               final SamlObjectSignatureValidator samlObjectSignatureValidator,
                                               final HostnameVerifier hostnameVerifier) {
    super(samlObjectSigner,
            parserPool,
            authenticationSystemSupport,
            servicesManager,
            webApplicationServiceFactory,
            samlRegisteredServiceCachingMetadataResolver,
            configBean,
            responseBuilder,
            authenticationContextClassMappings,
            serverPrefix,
            serverName,
            authenticationContextRequestParameter,
            loginUrl,
            logoutUrl,
            forceSignedLogoutRequests,
            singleLogoutCallbacksDisabled,
            samlObjectSignatureValidator);
    this.hostnameVerifier = hostnameVerifier;
}
 
Example 29
Project: CXJPadProject   File: OKClient.java   View source code 5 votes vote down vote up
public OKClient() {
    client = new OkHttpClient.Builder()
            .connectTimeout(HttpUtils.CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
            .readTimeout(HttpUtils.READ_TIMEOUT, TimeUnit.MILLISECONDS)
            .writeTimeout(HttpUtils.READ_TIMEOUT, TimeUnit.MILLISECONDS)
            .hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            })
            .build();
}
 
Example 30
Project: beadledom   File: X509HostnameVerifierAdapter.java   View source code 5 votes vote down vote up
/**
 * Adapts a {@link HostnameVerifier} to be compatible with the HttpClient
 * {@link X509HostnameVerifier}.
 */
public static X509HostnameVerifier adapt(HostnameVerifier verifier) {
  if (verifier == null) {
    throw new NullPointerException("verifier:null");
  }

  if (verifier instanceof X509HostnameVerifier) {
    return (X509HostnameVerifier) verifier;
  }

  return new X509HostnameVerifierAdapter(verifier);
}
 
Example 31
Project: dremio-oss   File: SSLHelper.java   View source code 5 votes vote down vote up
/**
 * We will accept all hostnames
 * @return
 */
public static HostnameVerifier newAllValidHostnameVerifier() {
  return new HostnameVerifier() {
    @Override
    public boolean verify(String hostname, SSLSession session) {
      return true;
    }
  };
}
 
Example 32
Project: JRediClients   File: JedisFactory.java   View source code 5 votes vote down vote up
public JedisFactory(final String host, final int port, final int connectionTimeout, final int soTimeout,
		final String password, final int database, final String clientName, final boolean ssl,
		final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
		final HostnameVerifier hostnameVerifier) {
	this.hostAndPort.set(new HostAndPort(host, port));
	this.connectionTimeout = connectionTimeout;
	this.soTimeout = soTimeout;
	this.password = password;
	this.database = database;
	this.clientName = clientName;
	this.ssl = ssl;
	this.sslSocketFactory = sslSocketFactory;
	this.sslParameters = sslParameters;
	this.hostnameVerifier = hostnameVerifier;
}
 
Example 33
Project: pcloud-networking-java   File: PCloudAPIClient.java   View source code 5 votes vote down vote up
/**
 * Sets the {@linkplain HostnameVerifier} for the client
 *
 * @param hostnameVerifier The {@linkplain HostnameVerifier} to be set to the client
 * @return A reference to the {@linkplain Builder} object
 * @throws IllegalArgumentException on a null {@linkplain HostnameVerifier} argument
 */
public Builder setHostnameVerifier(HostnameVerifier hostnameVerifier) {
    if (hostnameVerifier == null) {
        throw new IllegalArgumentException("HostnameVerifier cannot be null.");
    }
    this.hostnameVerifier = hostnameVerifier;
    return this;
}
 
Example 34
Project: JRediClients   File: JedisPool.java   View source code 5 votes vote down vote up
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, int timeout,
		final String password, final int database, final String clientName, final boolean ssl,
		final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
		final HostnameVerifier hostnameVerifier) {
	this(poolConfig, host, port, timeout, timeout, password, database, clientName, ssl, sslSocketFactory,
			sslParameters, hostnameVerifier);
}
 
Example 35
Project: JRediClients   File: JedisPool.java   View source code 5 votes vote down vote up
public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, final int connectionTimeout,
		final int soTimeout, final String password, final int database, final String clientName, final boolean ssl,
		final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
		final HostnameVerifier hostnameVerifier) {
	super(poolConfig, new JedisFactory(host, port, connectionTimeout, soTimeout, password, database, clientName,
			ssl, sslSocketFactory, sslParameters, hostnameVerifier));
}
 
Example 36
Project: JRediClients   File: JedisPool.java   View source code 5 votes vote down vote up
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, final int connectionTimeout,
		final int soTimeout, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
		final HostnameVerifier hostnameVerifier) {
	super(poolConfig, new JedisFactory(uri, connectionTimeout, soTimeout, null,
					(uri.getScheme() != null && uri.getScheme().equals("rediss")), sslSocketFactory, sslParameters,
					hostnameVerifier));
}
 
Example 37
Project: OpenJSharp   File: HttpClientTransport.java   View source code 5 votes vote down vote up
protected boolean checkHTTPS(HttpURLConnection connection) {
    if (connection instanceof HttpsURLConnection) {

        // TODO The above property needs to be removed in future version as the semantics of this property are not preoperly defined.
        // One should use JAXWSProperties.HOSTNAME_VERIFIER to control the behavior

        // does the client want client hostname verification by the service
        String verificationProperty =
            (String) context.invocationProperties.get(HOSTNAME_VERIFICATION_PROPERTY);
        if (verificationProperty != null) {
            if (verificationProperty.equalsIgnoreCase("true")) {
                ((HttpsURLConnection) connection).setHostnameVerifier(new HttpClientVerifier());
            }
        }

        // Set application's HostNameVerifier for this connection
        HostnameVerifier verifier =
            (HostnameVerifier) context.invocationProperties.get(JAXWSProperties.HOSTNAME_VERIFIER);
        if (verifier != null) {
            ((HttpsURLConnection) connection).setHostnameVerifier(verifier);
        }

        // Set application's SocketFactory for this connection
        SSLSocketFactory sslSocketFactory =
            (SSLSocketFactory) context.invocationProperties.get(JAXWSProperties.SSL_SOCKET_FACTORY);
        if (sslSocketFactory != null) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
        }

        return true;
    }
    return false;
}
 
Example 38
Project: JRediClients   File: BinaryJedis.java   View source code 5 votes vote down vote up
public BinaryJedis(final URI uri, final int connectionTimeout, final int soTimeout,
		final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
		final HostnameVerifier hostnameVerifier) {
	initializeClientFromURI(uri, sslSocketFactory, sslParameters, hostnameVerifier);
	client.setConnectionTimeout(connectionTimeout);
	client.setSoTimeout(soTimeout);
}
 
Example 39
Project: ScriptSpider   File: HttpUtils.java   View source code 5 votes vote down vote up
/**
 * 创建httpclient连接池,并初始化httpclient
 */
public void init() {
    try {
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,
                new TrustSelfSignedStrategy())
                .build();
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext, hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslsf)
                .build();
        httpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        // Increase max total connection to 200
        httpClientConnectionManager.setMaxTotal(maxTotalPool);
        // Increase default max connection per route to 20
        httpClientConnectionManager.setDefaultMaxPerRoute(maxConPerRoute);
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeout).build();
        httpClientConnectionManager.setDefaultSocketConfig(socketConfig);
    } catch (Exception e) {

    }
}
 
Example 40
Project: JRediClients   File: JedisShardInfo.java   View source code 5 votes vote down vote up
public JedisShardInfo(String host, int port, int connectionTimeout, int soTimeout, int weight, boolean ssl,
		SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, HostnameVerifier hostnameVerifier) {
	super(weight);
	this.host = host;
	this.port = port;
	this.connectionTimeout = connectionTimeout;
	this.soTimeout = soTimeout;
	this.ssl = ssl;
	this.sslSocketFactory = sslSocketFactory;
	this.sslParameters = sslParameters;
	this.hostnameVerifier = hostnameVerifier;
}