Jexxer
Jexxer

Reputation: 13

Disable SSL certification in websocket java

I have java websocket connection that tries to login to the server followed by establishing the websocket connection. The websocket class has the mechanism to connect the socket connection where's the main class call for the websocket class constructor.

WebSocket(URI serverUri, Map<String, String> head) {
        super(serverUri, head);
    }
socketUri = new URI(sockPath);
Map<String, String> head = new HashMap<>();
head.put("Authorization", "Bearer ".concat(headerToken));
client = new WebSocket(websocketUri, head);
client.setServerWebSocketUrlPathsockPath);
client.connect();

How to make the socket connection to disable the SSL certificate check.

Upvotes: 1

Views: 3002

Answers (1)

Flav
Flav

Reputation: 190

While disabling SSL certificate checks is not good practice, here is a solution:

The following code comes from Nakov.com

    // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            }
        };
 
        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
 
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
 
        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

Upvotes: 1

Related Questions