下面列出了怎么用javax.net.ssl.HostnameVerifier的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
private void assertSSLHostnameVerifier(Class<? extends HostnameVerifier> expected,
SocketFactoryRegistryProvider provider) {
ConnectionSocketFactory socketFactory = provider.getSocketFactoryRegistry().lookup("https");
assertNotNull("unable to lookup https", socketFactory);
assertTrue("socketFactory is not an SSLConnectionSocketFactory: " + socketFactory.getClass(),
socketFactory instanceof SSLConnectionSocketFactory);
SSLConnectionSocketFactory sslSocketFactory = (SSLConnectionSocketFactory) socketFactory;
try {
Object hostnameVerifier = FieldUtils.readField(sslSocketFactory, "hostnameVerifier", true);
assertNotNull("sslSocketFactory has null hostnameVerifier", hostnameVerifier);
assertEquals("sslSocketFactory does not have expected hostnameVerifier impl",
expected, hostnameVerifier.getClass());
} catch (IllegalAccessException e) {
throw new AssertionError("Unexpected access error reading hostnameVerifier field", e);
}
}
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);
}
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;
}
});
}
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);
}
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();
}
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);
}
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);
}
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;
}
private Registry<ConnectionSocketFactory> createConnectionSocketFactory() {
HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(PublicSuffixMatcherLoader.getDefault());
ConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContextOverride != null ?
sslContextOverride : defaultSslContext, sslSupportedProtocols, null, hostnameVerifier);
return RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslSocketFactory)
.build();
}
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;
}
public HostnameVerifier createHostnameVerifier() {
if (config.isVerifySslCertificatesOfServices()) {
return SSLConnectionSocketFactory.getDefaultHostnameVerifier();
} else {
return new NoopHostnameVerifier();
}
}
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();
}
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);
}
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;
}
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;
}
/**
* 忽略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);
}
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();
}
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;
}
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());
}
/**
* 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;
}
public static ConfigServerApiImpl create(ConfigServerInfo info,
ServiceIdentityProvider provider,
HostnameVerifier hostnameVerifier) {
return new ConfigServerApiImpl(
info.getConfigServerUris(),
hostnameVerifier,
provider);
}
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;
}
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);
}
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;
}
@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);
}
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;
}
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.");
}
}
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);
}
}
public static HostnameVerifier trustAllVerifier() {
HostnameVerifier allHostsValid = (String hostname, SSLSession session) -> {
// logger.debug(hostname + " " + session.getPeerHost() + " " + session.getProtocol() + " " + session.getCipherSuite());
return true;
};
return allHostsValid;
}