Example usage for javax.net.ssl HttpsURLConnection getDefaultSSLSocketFactory

List of usage examples for javax.net.ssl HttpsURLConnection getDefaultSSLSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection getDefaultSSLSocketFactory.

Prototype

public static SSLSocketFactory getDefaultSSLSocketFactory() 

Source Link

Document

Gets the default static SSLSocketFactory that is inherited by new instances of this class.

Usage

From source file:de.unidue.stud.sehawagn.oidcclient.SimpleOIDCClient.java

public void requestToken() {
    AuthorizationGrant grant;/*from  ww  w  .  j  a  v a 2s .com*/
    if (authCode == null) {
        if (resourceOwnerCredentialsGrant == null) {
            System.err
                    .println("Authentication Code is null and no user/password set, stopping token retrieval");
            return;
        } else {
            grant = resourceOwnerCredentialsGrant;
        }
    } else {
        grant = new AuthorizationCodeGrant(authCode, redirectURI);
    }
    TokenRequest tokenReq = new TokenRequest(providerMetadata.getTokenEndpointURI(),
            new ClientSecretBasic(clientID, clientInformation.getSecret()), grant);

    HTTPResponse tokenHTTPResp = null;
    try {
        tokenHTTPResp = tokenReq.toHTTPRequest().send(HttpsURLConnection.getDefaultHostnameVerifier(),
                HttpsURLConnection.getDefaultSSLSocketFactory());
    } catch (SerializeException | IOException e) {
        // TODO proper error handling
        e.printStackTrace();
    }

    // Parse and check response
    TokenResponse tokenResponse = null;
    try {
        tokenResponse = OIDCTokenResponseParser.parse(tokenHTTPResp);
    } catch (ParseException e) {
        // TODO proper error handling
        e.printStackTrace();
    }

    if (tokenResponse instanceof TokenErrorResponse) {
        ErrorObject error = ((TokenErrorResponse) tokenResponse).getErrorObject();
        // TODO error handling
        System.err.println("Error at token retrieval");
        System.err.println(error);
        return;
    }

    OIDCTokenResponse accessTokenResponse = (OIDCTokenResponse) tokenResponse;
    accessToken = accessTokenResponse.getOIDCTokens().getAccessToken();
    idToken = accessTokenResponse.getOIDCTokens().getIDToken();
}

From source file:de.unidue.stud.sehawagn.oidcclient.SimpleOIDCClient.java

public void requestUserInfo() {
    if (accessToken == null) {
        System.err.println("Access Token null, stopping UserInfo retrieval");
        return;/*from  ww w.j  a v  a2 s .c o  m*/
    }

    UserInfoRequest userInfoReq = new UserInfoRequest(userInfoEndpointURI, (BearerAccessToken) accessToken);

    HTTPResponse userInfoHTTPResp = null;
    try {
        userInfoHTTPResp = userInfoReq.toHTTPRequest().send(HttpsURLConnection.getDefaultHostnameVerifier(),
                HttpsURLConnection.getDefaultSSLSocketFactory());
    } catch (SerializeException | IOException e) {
        // TODO proper error handling
        e.printStackTrace();
    }

    UserInfoResponse userInfoResponse = null;
    try {
        userInfoResponse = UserInfoResponse.parse(userInfoHTTPResp);
    } catch (ParseException e) {
        // TODO proper error handling
        e.printStackTrace();
    }

    if (userInfoResponse instanceof UserInfoErrorResponse) {
        UserInfoErrorResponse errorResponse = ((UserInfoErrorResponse) userInfoResponse);
        ErrorObject error = errorResponse.getErrorObject();

        System.err.println(errorResponse.indicatesSuccess());
        System.err.println("Userinfo retrieval failed:");
        System.err.println(errorResponse);
        System.err.println(error);
        System.err.println(error.getHTTPStatusCode());
        System.err.println(userInfoHTTPResp.getStatusCode());
        System.err.println(userInfoHTTPResp.getContent());
        System.err.println(userInfoHTTPResp.getWWWAuthenticate());
        System.err.println(userInfoHTTPResp.getLocation());
    }

    UserInfoSuccessResponse successResponse = (UserInfoSuccessResponse) userInfoResponse;
    userInfoClaims = successResponse.getUserInfo().toJSONObject();
}

From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java

/**
 * SSL?TrustManager???SSL?/*  w ww  .j a  va  2  s .  com*/
 * HttpsURLConnection????
 */
private void trustAllHosts() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };

    // all-trusting TrustManager
    try {
        // ?SSL
        mDefaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
        // TrustManager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        XLog.e(CLASS_NAME, e.getMessage());
    }
}

From source file:org.elasticsearch.plugins.PluginManagerIT.java

public void testThatBasicAuthIsSupportedWithHttps() throws Exception {
    assumeTrue("test requires security manager to be disabled", System.getSecurityManager() == null);

    SSLSocketFactory defaultSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    ServerBootstrap serverBootstrap = new ServerBootstrap(new NioServerSocketChannelFactory());
    SelfSignedCertificate ssc = new SelfSignedCertificate("localhost");

    try {//from  w  ww.j  ava 2 s  .c o m

        //  Create a trust manager that does not validate certificate chains:
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        final List<HttpRequest> requests = new ArrayList<>();
        final SslContext sslContext = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());

        serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(new SslHandler(sslContext.newEngine()), new HttpRequestDecoder(),
                        new HttpResponseEncoder(), new LoggingServerHandler(requests));
            }
        });

        Channel channel = serverBootstrap.bind(new InetSocketAddress(InetAddress.getByName("localhost"), 0));
        int port = ((InetSocketAddress) channel.getLocalAddress()).getPort();
        // IO_ERROR because there is no real file delivered...
        assertStatus(
                String.format(Locale.ROOT,
                        "install https://user:pass@localhost:%s/foo.zip --verbose --timeout 1s", port),
                ExitStatus.IO_ERROR);

        // ensure that we did not try any other data source like download.elastic.co, in case we specified our own local URL
        assertThat(terminal.getTerminalOutput(), not(hasItem(containsString("download.elastic.co"))));

        assertThat(requests, hasSize(1));
        String msg = String.format(Locale.ROOT,
                "Request header did not contain Authorization header, terminal output was: %s",
                terminal.getTerminalOutput());
        assertThat(msg, requests.get(0).headers().contains("Authorization"), is(true));
        assertThat(msg, requests.get(0).headers().get("Authorization"),
                is("Basic " + Base64.encodeBytes("user:pass".getBytes(StandardCharsets.UTF_8))));
    } finally {
        HttpsURLConnection.setDefaultSSLSocketFactory(defaultSocketFactory);
        serverBootstrap.releaseExternalResources();
        ssc.delete();
    }
}