Home » Swift » WSS/TLS websocket connection with Swift iOS

WSS/TLS websocket connection with Swift iOS

Posted by: admin January 9, 2018 Leave a comment

Questions:

SOLVED (following answer)

I am using Starscream library to create a safe websocket wss in the test server we have a self-signed certificate and I find it impossible to make the connection.

var socket = WebSocket(url: NSURL(scheme: "wss", host: "selfsignedserver.com", path: "/")!)

Log

2014-12-16 10:38:10.260 pruebasignin[2135:363455] CFNetwork SSLHandshake failed (-9807)
websocket is disconnected: The operation couldn’t be completed. (OSStatus error -9807.)

and when I try to connect to a server certificate valid also fails to connect
SOLVED

var socket = WebSocket(url: NSURL(scheme: "wss", host: "production.com", path: "/")!)

Log

websocket is disconnected: Invalid HTTP upgrade
Answers:

Starscream now supports a flag so you can use self-signed certificates:
https://github.com/daltoniam/Starscream#self-signed-ssl-and-voip

Questions:
Answers:

I solved the problem by allowing self-signed certificates Starscream modifying the library.
To this must be added the arcivo WebSocket.swift the following code:

if url.scheme == "wss" || url.scheme == "https" {
        inputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
        outputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)

        /* My code */
        var settings = Dictionary<NSObject, NSObject>()
        settings[kCFStreamSSLValidatesCertificateChain] = NSNumber(bool:false)
        settings[kCFStreamSSLPeerName] = kCFNull

        CFReadStreamSetProperty(self.inputStream, kCFStreamPropertySSLSettings, settings)
        CFWriteStreamSetProperty(self.outputStream, kCFStreamPropertySSLSettings, settings)
        /* End my code*/

    }