'How to use webSocketOptions.AllowedOrigins?

I have an ASP web app.

The app opens a websocket communication server. The websocket server works properly.

var webSocketOptions = new WebSocketOptions()
        {
            KeepAliveInterval = TimeSpan.FromSeconds(120),
        };                        
app.UseWebSockets(webSocketOptions);

app.Use(async (context, next) =>
{
    if (context.Request.Path == "/ws")
    {
        if (context.WebSockets.IsWebSocketRequest)
        {
            using (WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync())
            {
                //do some stuff
            }
        }
        else
        {
            context.Response.StatusCode = 400;
        }
    }
    else
    {
        await next();
    }

});

When I open my domain example.com and go to Chrome Web Console, the following code works :

var socket = new WebSocket("wss://www.example.com/ws");

However when I add the security constraint :

webSocketOptions.AllowedOrigins.Add("https://www.example.com");

The websocket connection doesn't work anymore. I'm getting the error

VM376:1 WebSocket connection to 'wss://www.example.com/ws' failed: Error during WebSocket handshake: Unexpected response code: 403

Can anyone help please on how to use webSocketOptions.AllowedOrigins ?

I want the Websocket access be allowed only when a request is made from my website www.example.com

Thanks



Solution 1:[1]

You have to configure "webSocketOptions.AllowedOrigins" inside your startup middleWare

here a microsoft websocket doc:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/websockets?view=aspnetcore-3.1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris Catignani