How to authenticate Websocket connections in C#

Viewed 593

I have an HTML application.

Some pages have to run websockets to connect to a server running an Asp.Net application and send/receive some messages through Websocket.

The websockets server works fine. But anyone can send some requests to the server. I would like my server to be protected and receives only authenticated requests. For example from Javascript in Developer Mode, I can run requests against Websocket server...

So far I'm accepting requests only from my domain as follows but that is not enough :

    var webSocketOptions = new WebSocketOptions()
    {
        KeepAliveInterval = TimeSpan.FromSeconds(120),
    };
    webSocketOptions.AllowedOrigins.Add("https://example.com");
    webSocketOptions.AllowedOrigins.Add("https://www.example.com");

    app.UseWebSockets(webSocketOptions);

Is there any way to authenticate Websocket requests ? Or for example allow only legitimate users send requests to the WS server ?

Thanks.

1 Answers

I hope someone else could provide more information - as I am not very familiar with WS(Web Sockets), but here what I would do (number 3 is probably what you want):

  1. Validate Before WS connection is established - Self explanatory, don't create a WS connection if they had not authenticated via another method, but that's not always the option;

  2. Use a specified format with a validation built it - Lets say the socket is expecting a message in the form of:

    { "Token": "27e0127341dfaojo", "Message": "Hello World!", "Command": "SendMessage" }

If it is not in that format, then ignore it - and once it is, you can validate the token.

  1. Using (Cookie Authentication) - the link explains more.
Related