B4J Question [Server] websocket SSL Connections - redirect to HTTPS port

aminoacid

Active Member
Licensed User
Longtime User
I have been working on creating a keystore for my Lets Encrypt certificates so that I can use them with a websockets server. In order to test out the keystore and keep things simple, I modified the following "Hello World" webapp example to use SSL with my keystore.


My modifications to the above example and the keystore work great and I can access the web application on both the HTTP and HTTPS ports
(BTW - If anyone is interested in the instructions to create a keystore using Lets Encrypt certificates, let me know and I'll be glad to post them here)

Here is the modified code for the Hello World webapp using SSL and based on Erel's Server SSL tutorial: https://www.b4x.com/android/forum/threads/server-ssl-connections.40130/

Hello World SSL:
Sub AppStart (Args() As String)
    srvr.Initialize("srvr")
    ConfigureSSL(8443)                        '<---- HTTPS Port
    srvr.AddWebSocket("/ws", "HelloWorld")
    srvr.Port = 51042                        '<---- HTTP Port
    srvr.Start
    StartMessageLoop
End Sub

Private Sub ConfigureSSL (SslPort As Int)
    Dim ssl As SslConfiguration
    ssl.Initialize
    ssl.SetKeyStorePath(File.DirApp, "web.keystore")             'path to keystore file
    ssl.KeyStorePassword = "hello123"
    ssl.KeyManagerPassword = "hello123"
    srvr.SetSslConfiguration(ssl, SslPort)
    'add filter to redirect all traffic from http to https (optional) - not applicable to websockets
    'srvr.AddFilter("/*", "HttpsFilter", False)
End Sub

The only thing I cannot figure out is how to redirect traffic from the HTTP to HTTPS port in the application. Erel's tutorial mentions that the filter he includes in the post does not apply to websockets and we should use "WebSocket.Secure to make sure that a secure connection has been made ...." but I can't figure out how to do this.

Any suggestions?

Thanks!
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
It is indeed a bit confusing. The browser sends a regular request to the html page and then the WebSocket connection is initiated by the JavaScript code.
The filter is applied to the regular request. In the case of a browser it is exactly what you need. If you try to programmatically connect to the WebSocket, for example with this library: https://www.b4x.com/android/forum/threads/websocket-client-library.40221/#content, the filter will not do anything.
 
Upvote 0
Top