javax.net.ssl.HostnameVerifier Java Examples

The following examples show how to use javax.net.ssl.HostnameVerifier. 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: OAuthAuthenticator.java    From strimzi-kafka-oauth with Apache License 2.0 6 votes vote down vote up
public static TokenInfo loginWithClientSecret(URI tokenEndpointUrl, SSLSocketFactory socketFactory,
                                              HostnameVerifier hostnameVerifier,
                                              String clientId, String clientSecret, boolean isJwt,
                                              PrincipalExtractor principalExtractor, String scope) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("loginWithClientSecret() - tokenEndpointUrl: {}, clientId: {}, clientSecret: {}, scope: {}",
                tokenEndpointUrl, clientId, mask(clientSecret), scope);
    }

    String authorization = "Basic " + base64encode(clientId + ':' + clientSecret);

    StringBuilder body = new StringBuilder("grant_type=client_credentials");
    if (scope != null) {
        body.append("&scope=").append(urlencode(scope));
    }

    return post(tokenEndpointUrl, socketFactory, hostnameVerifier, authorization, body.toString(), isJwt, principalExtractor);
}
 
Example #2
Source File: OkHttpClientTransport.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
OkHttpClientTransport(InetSocketAddress address, String authority, @Nullable String userAgent,
    Executor executor, @Nullable SSLSocketFactory sslSocketFactory,
    @Nullable HostnameVerifier hostnameVerifier, ConnectionSpec connectionSpec,
    int maxMessageSize, int initialWindowSize, @Nullable ProxyParameters proxy,
    Runnable tooManyPingsRunnable, int maxInboundMetadataSize, TransportTracer transportTracer) {
  this.address = Preconditions.checkNotNull(address, "address");
  this.defaultAuthority = authority;
  this.maxMessageSize = maxMessageSize;
  this.initialWindowSize = initialWindowSize;
  this.executor = Preconditions.checkNotNull(executor, "executor");
  serializingExecutor = new SerializingExecutor(executor);
  // Client initiated streams are odd, server initiated ones are even. Server should not need to
  // use it. We start clients at 3 to avoid conflicting with HTTP negotiation.
  nextStreamId = 3;
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
  this.connectionSpec = Preconditions.checkNotNull(connectionSpec, "connectionSpec");
  this.stopwatchFactory = GrpcUtil.STOPWATCH_SUPPLIER;
  this.userAgent = GrpcUtil.getGrpcUserAgent("okhttp", userAgent);
  this.proxy = proxy;
  this.tooManyPingsRunnable =
      Preconditions.checkNotNull(tooManyPingsRunnable, "tooManyPingsRunnable");
  this.maxInboundMetadataSize = maxInboundMetadataSize;
  this.transportTracer = Preconditions.checkNotNull(transportTracer);
  initTransportTracer();
}
 
Example #3
Source File: URLConnectionUtils.java    From Eagle with Apache License 2.0 6 votes vote down vote up
public static URL getHTTPSUrl(String urlString) throws MalformedURLException, NoSuchAlgorithmException, KeyManagementException  {
   	// Create a trust manager that does not validate certificate chains   
       final TrustManager[] trustAllCerts = new TrustManager[] {new TrustAllX509TrustManager()};
       // Install the all-trusting trust manager   
       final SSLContext sc = SSLContext.getInstance("SSL");   
       sc.init(null, trustAllCerts, new java.security.SecureRandom());   
       HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());   
       // Create all-trusting host name verifier   
       final HostnameVerifier allHostsValid = new HostnameVerifier() {   
           public boolean verify(String hostname, SSLSession session) {   
               return true;   
           }   
       };
       HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
       return new URL(urlString);
}
 
Example #4
Source File: OkHttpUtil.java    From AndroidStudyDemo with GNU General Public License v2.0 6 votes vote down vote up
private OkHttpUtil() {
    OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
    // cookie enabled
    okHttpClientBuilder.cookieJar(new SimpleCookieJar());
    this.mDelivery = new Handler(Looper.getMainLooper());

    if (true) {
        okHttpClientBuilder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    }
    this.mOkHttpClient = okHttpClientBuilder.build();
}
 
Example #5
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 #6
Source File: SecurityUtils.java    From wildfly-camel-examples with Apache License 2.0 6 votes vote down vote up
public static SSLConnectionSocketFactory createSocketFactory(Path truststoreFile, Path keystoreFile, String password)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException {
    final char[] pwd = password.toCharArray();
    SSLContextBuilder sslcontextBuilder = SSLContexts.custom()
            .loadTrustMaterial(truststoreFile.toFile(), pwd, TrustSelfSignedStrategy.INSTANCE)
    ;
    if (keystoreFile != null) {
        sslcontextBuilder.loadKeyMaterial(keystoreFile.toFile(), pwd, pwd);
    }

    sslcontextBuilder.setProtocol("TLSv1.2");

    return new SSLConnectionSocketFactory(sslcontextBuilder.build(), new HostnameVerifier() {
        @Override
        public boolean verify(final String s, final SSLSession sslSession) {
            return true;
        }
    });
}
 
Example #7
Source File: CookieHttpsClientTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
void doClientSide() throws Exception {
    // Wait for server to get started.
    while (!serverReady) {
        Thread.sleep(50);
    }

    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }});

    URL url = new URL("https://localhost:" + serverPort +"/");

    // Run without a CookieHandler first
    InputStream in = url.openConnection().getInputStream();
    while (in.read() != -1);  // read response body so connection can be reused

    // Set a CookeHandler and retest using the HttpClient from the KAC
    CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(manager);

    in = url.openConnection().getInputStream();
    while (in.read() != -1);

    if (manager.getCookieStore().getCookies().isEmpty()) {
        throw new RuntimeException("Failed: No cookies in the cookie Handler.");
    }
}
 
Example #8
Source File: SSLHelper.java    From QuickDevFramework with Apache License 2.0 5 votes vote down vote up
/**
 * generate a https HostNameVerifier with inputted urls
 * @param hostUrls accept host urls
 */
public static HostnameVerifier getHostnameVerifier(final String[] hostUrls) {
    return (hostname, session) -> {
        boolean ret = false;
        for (String host : hostUrls) {
            if (host.equalsIgnoreCase(hostname)) {
                ret = true;
            }
        }
        return ret;
    };
}
 
Example #9
Source File: ScepClient.java    From xipki with Apache License 2.0 5 votes vote down vote up
public ScepClient(CaIdentifier caId, CaCertValidator caCertValidator,
    SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier)
    throws MalformedURLException {
  super(caId, caCertValidator);
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
}
 
Example #10
Source File: Address.java    From phonegap-plugin-loading-spinner with Apache License 2.0 5 votes vote down vote up
public Address(String uriHost, int uriPort, SSLSocketFactory sslSocketFactory,
    HostnameVerifier hostnameVerifier, Proxy proxy) throws UnknownHostException {
  if (uriHost == null) throw new NullPointerException("uriHost == null");
  if (uriPort <= 0) throw new IllegalArgumentException("uriPort <= 0: " + uriPort);
  this.proxy = proxy;
  this.uriHost = uriHost;
  this.uriPort = uriPort;
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
}
 
Example #11
Source File: QNUploader.java    From SmartIM with Apache License 2.0 5 votes vote down vote up
public QNUploader() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.cookieJar(cookieJar);
    builder.hostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    });
    this.client = builder.build();
}
 
Example #12
Source File: HttpRetrofit.java    From GankGirl with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param hostUrls
 * @return
 */
private static HostnameVerifier getHostnameVerifier(final String[] hostUrls) {
    return (hostname, session) -> {
        boolean ret = false;
        for (String host : hostUrls) {
            if (host.equalsIgnoreCase(hostname)) {
                ret = true;
            }
        }
        return ret;
    };
}
 
Example #13
Source File: SSOAgentConfig.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private void doHostNameVerification(){
    if (!this.getEnableHostNameVerification()) {
        // Create empty HostnameVerifier
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }
}
 
Example #14
Source File: KeycloakRBACAuthorizer.java    From strimzi-kafka-oauth with Apache License 2.0 5 votes vote down vote up
static HostnameVerifier createHostnameVerifier(Config config) {
    String hostCheck = ConfigUtil.getConfigWithFallbackLookup(config,
            AuthzConfig.STRIMZI_AUTHORIZATION_SSL_ENDPOINT_IDENTIFICATION_ALGORITHM, Config.OAUTH_SSL_ENDPOINT_IDENTIFICATION_ALGORITHM);

    if (hostCheck == null) {
        hostCheck = "HTTPS";
    }
    // Following Kafka convention for skipping hostname validation (when set to <empty>)
    return "".equals(hostCheck) ? SSLUtil.createAnyHostHostnameVerifier() : null;
}
 
Example #15
Source File: CookieHttpsClientTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void doClientSide() throws Exception {
    // Wait for server to get started.
    while (!serverReady) {
        Thread.sleep(50);
    }

    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }});

    URL url = new URL("https://localhost:" + serverPort +"/");

    // Run without a CookieHandler first
    InputStream in = url.openConnection().getInputStream();
    while (in.read() != -1);  // read response body so connection can be reused

    // Set a CookeHandler and retest using the HttpClient from the KAC
    CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(manager);

    in = url.openConnection().getInputStream();
    while (in.read() != -1);

    if (manager.getCookieStore().getCookies().isEmpty()) {
        throw new RuntimeException("Failed: No cookies in the cookie Handler.");
    }
}
 
Example #16
Source File: WaspBuilderTest.java    From wasp with Apache License 2.0 5 votes vote down vote up
@Test
public void testWaspHttpStackCustom() throws Exception {

  class MyHttpStack implements WaspHttpStack {

    @Override
    public HttpStack getHttpStack() {
      return new OkHttpStack(new OkHttpClient());
    }

    @Override
    public void setHostnameVerifier(HostnameVerifier hostnameVerifier) {

    }

    @Override
    public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) {

    }

    @Override
    public void setCookieHandler(CookieHandler cookieHandler) {

    }
  }

  Wasp.Builder builder = new Wasp.Builder(context)
      .setWaspHttpStack(new MyHttpStack())
      .setEndpoint("http");
  builder.build();

  //default should be NONE
  assertThat(builder.getWaspHttpStack()).isInstanceOf(MyHttpStack.class);
}
 
Example #17
Source File: NetworkTools.java    From MyBox with Apache License 2.0 5 votes vote down vote up
public static HostnameVerifier trustAllVerifier() {
        HostnameVerifier allHostsValid = (String hostname, SSLSession session) -> {
//            logger.debug(hostname + "  " + session.getPeerHost() + "  " + session.getProtocol() + "  " + session.getCipherSuite());
            return true;
        };
        return allHostsValid;
    }
 
Example #18
Source File: TracingJedisPool.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
public TracingJedisPool(final GenericObjectPoolConfig poolConfig, 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,
    TracingConfiguration tracingConfiguration) {

  super(poolConfig, host, port, connectionTimeout, soTimeout, password, database, clientName, ssl,
      sslSocketFactory, sslParameters, hostnameVerifier);
  this.tracingConfiguration = tracingConfiguration;
}
 
Example #19
Source File: Address.java    From crosswalk-cordova-android with Apache License 2.0 5 votes vote down vote up
public Address(String uriHost, int uriPort, SSLSocketFactory sslSocketFactory,
    HostnameVerifier hostnameVerifier, OkAuthenticator authenticator, Proxy proxy,
    List<String> transports) throws UnknownHostException {
  if (uriHost == null) throw new NullPointerException("uriHost == null");
  if (uriPort <= 0) throw new IllegalArgumentException("uriPort <= 0: " + uriPort);
  if (authenticator == null) throw new IllegalArgumentException("authenticator == null");
  if (transports == null) throw new IllegalArgumentException("transports == null");
  this.proxy = proxy;
  this.uriHost = uriHost;
  this.uriPort = uriPort;
  this.sslSocketFactory = sslSocketFactory;
  this.hostnameVerifier = hostnameVerifier;
  this.authenticator = authenticator;
  this.transports = Util.immutableList(transports);
}
 
Example #20
Source File: SlbBuckConfig.java    From buck with Apache License 2.0 5 votes vote down vote up
public ClientSideSlb createClientSideSlb(
    Clock clock,
    BuckEventBus eventBus,
    Optional<HandshakeCertificates> handshakeCertificates,
    Optional<HostnameVerifier> hostnameVerifier) {
  return new ClientSideSlb(
      createConfig(clock, eventBus),
      createOkHttpClientBuilder(handshakeCertificates, hostnameVerifier));
}
 
Example #21
Source File: TracingJedisPool.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
public TracingJedisPool(final GenericObjectPoolConfig poolConfig, final URI uri,
    final SSLSocketFactory sslSocketFactory,
    final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier,
    TracingConfiguration tracingConfiguration) {
  super(poolConfig, uri, sslSocketFactory, sslParameters, hostnameVerifier);
  this.tracingConfiguration = tracingConfiguration;
}
 
Example #22
Source File: TracingJedisWrapper.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
public TracingJedisWrapper(final URI uri, final int timeout,
    final SSLSocketFactory sslSocketFactory,
    final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier,
    TracingConfiguration tracingConfiguration) {
  this.wrapped = new Jedis(uri, timeout, sslSocketFactory, sslParameters, hostnameVerifier);
  this.helper = new TracingHelper(tracingConfiguration);
}
 
Example #23
Source File: Address.java    From AndroidProjects with MIT License 5 votes vote down vote up
public Address(String uriHost, int uriPort, Dns dns, SocketFactory socketFactory,
    SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier,
    CertificatePinner certificatePinner, Authenticator proxyAuthenticator, 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 #24
Source File: ConfigServerApiImpl.java    From vespa with Apache License 2.0 5 votes vote down vote up
public static ConfigServerApiImpl create(ConfigServerInfo info,
                                         ServiceIdentityProvider provider,
                                         HostnameVerifier hostnameVerifier) {
    return new ConfigServerApiImpl(
            info.getConfigServerUris(),
            hostnameVerifier,
            provider);
}
 
Example #25
Source File: SSLFactory.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the hostname verifier it should be used in HttpsURLConnections.
 *
 * @return the hostname verifier.
 */
public HostnameVerifier getHostnameVerifier() {
  if (mode != Mode.CLIENT) {
    throw new IllegalStateException("Factory is in CLIENT mode");
  }
  return hostnameVerifier;
}
 
Example #26
Source File: TracingJedisPool.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
public TracingJedisPool(final GenericObjectPoolConfig poolConfig, final URI uri,
    final int connectionTimeout,
    final int soTimeout, final SSLSocketFactory sslSocketFactory,
    final SSLParameters sslParameters,
    final HostnameVerifier hostnameVerifier, TracingConfiguration tracingConfiguration) {
  super(poolConfig, uri, connectionTimeout, soTimeout, sslSocketFactory, sslParameters,
      hostnameVerifier);
  this.tracingConfiguration = tracingConfiguration;
}
 
Example #27
Source File: ConfigurationClientTest.java    From mapbox-events-android with MIT License 5 votes vote down vote up
private TelemetryClientSettings provideDefaultTelemetryClientSettings() {
  HttpUrl localUrl = obtainBaseEndpointUrl();

  return new TelemetryClientSettings.Builder(mock(Context.class))
    .baseUrl(localUrl)
    .sslSocketFactory(clientCertificates.sslSocketFactory())
    .x509TrustManager(clientCertificates.trustManager())
    .hostnameVerifier(new HostnameVerifier() {
      @Override
      public boolean verify(String hostname, SSLSession session) {
        return true;
      }
    })
    .build();
}
 
Example #28
Source File: LianlianSslUtils.java    From aaden-pay with Apache License 2.0 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) {
			System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
			return true;
		}
	};
	trustAllHttpsCertificates();
	HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
 
Example #29
Source File: IndexerSingleton.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private boolean createClientDocker()
{
	CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
	credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
	
	TrustStrategy trustStrategy = new TrustSelfSignedStrategy();
	SSLContext sslContext;
	try {
		sslContext = SSLContexts.custom().loadTrustMaterial(trustStrategy).build();
		HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
		
		RestClientBuilder restClientBuilder = createRestClientBuilder(hostname, scheme);
		
		restClientBuilder.setHttpClientConfigCallback(new HttpClientConfigCallback() {
			@Override
			public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
				httpClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(hostnameVerifier).build();
				httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
				return httpClientBuilder;
			}
		});

		return createHighLevelClient(restClientBuilder);
	} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
		logger.error("Error while creating secure connection to ElasticSearch: ", e);
	}
	
	return false;
}
 
Example #30
Source File: HttpRequest.java    From Android with MIT License 5 votes vote down vote up
private HttpRequest() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder()
            .connectTimeout(10000L, TimeUnit.MILLISECONDS)
            .readTimeout(10000L, TimeUnit.MILLISECONDS)
            .writeTimeout(10000L, TimeUnit.MILLISECONDS)
            .addInterceptor(new LoggerInterceptor(false))
            .hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
    mOkHttpClient = builder.build();
    mDelivery = new Handler(Looper.getMainLooper());
}