# Securing WebSocket Connections in ASP.NET Core using Sec WebSocket Protocol Header

> This article explores how to secure WebSocket connections in ASP.NET Core applications by utilizing the Sec-WebSocket-Protocol header for authentication and authorization purposes.

- **Author:** Bjoern Meyer
- **Published:** 2025-11-20
- **Modified:** 2025-11-29
- **Description:** This article explores how to secure WebSocket connections in ASP.NET Core applications by utilizing the Sec-WebSocket-Protocol header for authentication and authorization purposes.
- **4 min read** (619 words)
- **Tags:**
  - ASP.NET Core
  - HTML5
  - Middleware
  - Web Sockets
- **Web URL:** https://www.textcontrol.com/blog/2025/11/20/securing-websocket-connections-in-aspnet-core-using-sec-websocket-protocol-header/
- **LLMs URL:** https://www.textcontrol.com/blog/2025/11/20/securing-websocket-connections-in-aspnet-core-using-sec-websocket-protocol-header/llms.txt
- **LLMs-Full URL:** https://www.textcontrol.com/blog/2025/11/20/securing-websocket-connections-in-aspnet-core-using-sec-websocket-protocol-header/llms-full.txt

---

TX Text Control uses WebSocket connections for synchronization and state handling. To ensure that only authorized clients can access a document session, these connections must be protected.

Earlier implementations often passed authentication tokens through query strings. While this approach is simple, it raises several security concerns. The latest versions of TX Text Control offer a more secure and elegant solution with the WebSocketProtocols property. This property allows tokens to be passed using the Secure WebSocket Protocol header during the handshake.

This article explains why query string tokens should be avoided and how to use the WebSocketProtocols property. It also explains how to secure the server side with custom WebSocket security middleware.

### Why Query String Tokens Create Security Problems

Authentication data in a query string may appear unintentionally in many locations throughout your infrastructure. This includes:

- Web server request logs
- Reverse proxy logs and diagnostics
- Application monitoring systems
- Error tracking tools
- Browser history
- Analytics and traffic inspection tools

These logs may persist for months or even years, and they are often accessible to other systems or administrators. A clear text token appearing in a URL can easily be extracted and reused to hijack a WebSocket session.

Since WebSocket connections are long-lived, a leaked token can provide direct access to an active editing session. This is not acceptable for regulated environments such as finance, healthcare, or insurance.

### A Safer Approach with the Sec WebSocket Protocol Header

The new WebSocketProtocols property in TX Text Control enables the addition of custom protocol entries, which are automatically sent in the SEC WebSocket Protocol header during the handshake process. This eliminates the need for query strings.

```
@using TXTextControl.Web.MVC

@{
    var sAccessToken = "token_821e2f35-86e3-4917-a963-b0c4228d1315";
}

@Html.TXTextControl().TextControl(settings =>
{
    settings.WebSocketProtocols = new string[] { sAccessToken };
}).Render()
```

The token is sent as part of the handshake header and is not visible in URLs. Because the property is a simple string array, multiple entries can be added.

Since most servers do not log this header by default, the risk of accidental disclosure is significantly reduced.

### Validating the Token with Custom Middleware

In order to complete the security model, the server must validate each WebSocket handshake and reject any unauthorized connections. The middleware below verifies two things:

- The request is a TX Text Control WebSocket request
- The token transmitted through the Sec WebSocket Protocol header matches an expected value

```
public class WebSocketSecurityMiddleware
{
    private RequestDelegate m_next;

    // stored access token usually retrieved from any storage
    // implemented through OAuth or any other identity protocol
    private const string access_token = "821e2f35-86e3-4917-a963-b0c4228d1315";

    public WebSocketSecurityMiddleware(RequestDelegate next)
    {
        m_next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        // check if request is a TX Text Control WebSocket request
        if (context.WebSockets.IsWebSocketRequest &&
            context.WebSockets.WebSocketRequestedProtocols.Contains("TXTextControl.Web"))
        {
            string sAccess_token = context.WebSockets.WebSocketRequestedProtocols
                .FirstOrDefault(p => p.StartsWith("token_"))?.Substring(6) ?? string.Empty;

            if (sAccess_token != access_token)
                throw new UnauthorizedAccessException();
            else
                await m_next.Invoke(context);
        }
        else if (m_next != null)
        {
            await m_next.Invoke(context);
        }
    }
}
```

You can register this middleware in your ASP.NET Core pipeline:

```
app.UseMiddleware<WebSocketSecurityMiddleware>();
```

Add this middleware before the Text Control WebSocketHandler middleware to the pipeline.

```
// enable Web Sockets
app.UseWebSockets();

app.UseMiddleware<WebSocketSecurityMiddleware>();

// attach the Text Control WebSocketHandler middleware
app.UseTXWebSocketMiddleware();
```

The middleware intercepts the WebSocket setup request before the connection is established. If the token is invalid, the handshake fails, preventing the connection from being created.

### Conclusion

Using the Sec WebSocket Protocol header to transmit authentication tokens enhances the security of WebSocket connections within TX Text Control applications. Developers can effectively protect document sessions from unauthorized access by avoiding query strings and implementing custom middleware for validation.

---

## About Bjoern Meyer

As CEO, Bjoern is the visionary behind our strategic direction and business development, bridging the gap between our customers and engineering teams. His deep passion for coding and web technologies drives the creation of innovative products. If you're at a tech conference, be sure to stop by our booth - you'll most likely meet Bjoern in person. With an advanced graduate degree (Dipl. Inf.) in Computer Science, specializing in AI, from the University of Bremen, Bjoern brings significant expertise to his role. In his spare time, Bjoern enjoys running, paragliding, mountain biking, and playing the piano.

- [LinkedIn](https://www.linkedin.com/in/bjoernmeyer/)
- [X](https://x.com/txbjoern)
- [GitHub](https://github.com/bjoerntx)

---

## Related Posts

- [Adding a WebSocket Security Middleware to ASP.NET Core Web Applications](https://www.textcontrol.com/blog/2020/05/28/adding-a-websocket-security-middleware-to-aspnet-core/llms.txt)
- [Angular: Deploying the Backend TCP Service Separately](https://www.textcontrol.com/blog/2020/10/09/angular-deploying-the-backend-tcp-service-separately/llms.txt)
- [Securing the WebSocketHandler Endpoint in ASP.NET](https://www.textcontrol.com/blog/2020/05/28/securing-the-websockethandler-endpoint-in-aspnet/llms.txt)
