endel / NativeWebSocket

🔌 WebSocket client for Unity - with no external dependencies (WebGL, Native, Android, iOS, UWP)
Other
1.27k stars 161 forks source link

Wss Connection and authentication #41

Open AmineZouitine opened 3 years ago

AmineZouitine commented 3 years ago

Hi everyone, I am totally new to this and can't find a clear explanation of how to make this webSocket work.

I need to be able to connect to a WSS and put my login and password.

So if I have a url = wss://example.com a login = "pedro password = "issou

what should I do ? I saw that you can put headers but I don't know how it works, and when I test things I get errors :/

endel commented 3 years ago

Hi @AmineZouitine, if you're referring to HTTP basic-auth you need to provide an Authorization header with the credentials encoded in base64 format.

See more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization

EDIT: keep in mind that custom headers won't work on WebGL/Browser, as browsers don't provide a way to send custom headers.

AmineZouitine commented 3 years ago

Hi and thanks for your answer! So if I understand correctly, if I don't have a login and password to access my websocket I will be able to connect to a wss without any problem in Webgl?

Do you have an example of code to connect to wss and not ws? Because in the classic lib I have to put: sslConfiguration.enabledSSLProtocols = System.Security.Authentication.SslProtocls.tls12;

Because actually my code is :

async void Start()
{
    // websocket = new WebSocket("ws://echo.websocket.org");
    websocket = new WebSocket("wss://xxx.xxxxxx.com/ws2");

    websocket.OnOpen += () =>
    {
        Debug.Log("Connection open!");
    };

    websocket.OnError += (e) =>
    {
        Debug.Log("Error! " + e);
    };

    websocket.OnClose += (e) =>
    {
        Debug.Log("Connection closed!");
    };

    websocket.OnMessage += (bytes) =>
    {

    // Reading a plain text message
    var message = System.Text.Encoding.UTF8.GetString(bytes);
        Debug.Log("Received OnMessage! (" + bytes.Length + " bytes) " + message);
        value = message;
    };

    // Keep sending messages at every 0.3s
    //InvokeRepeating("SendWebSocketMessage", 0.0f, 0.3f);

    await websocket.Connect();
}

But when I launch my game i have this debug.Log : "Error! The Websocket request or response contained unsupported header(s)" 😞

Afamuefuna commented 2 years ago

Hello @endel I have the same authorization issue