Products Technologies Demo Docs Blog Support Company

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.

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

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.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

Related Posts

ASP.NET CoreHTML5Middleware

Adding a WebSocket Security Middleware to ASP.NET Core Web Applications

This article shows how to add a security middleware to ASP.NET Core Web Applications to secure the WebSocketHandler requests.


AngularASP.NET CoreDocument Editor

Angular: Deploying the Backend TCP Service Separately

The Angular document editor requires an ASP.NET or ASP.NET Core backend connected to the TCP Service to synchronize the rendering. This article explains how to deploy the TCP Service separately…


ASP.NETHTML5Web Sockets

Securing the WebSocketHandler Endpoint in ASP.NET

This article shows how to add a security layer by adding an authentication filter to an endpoint that creates the WebSocketHandler.

Summarize this blog post with:

Share on this blog post on: