An earlier article describes how an MVC filter is added to the WebSocketHandler endpoint to add a security layer to this connection. Read more details about when this is required and recommended in the mentioned article.

In ASP.NET Core Web Applications, the WebSocketHandler is added through a middleware. A middleware is code added to the app pipeline to handle specific requests.

The following class WebSocketSecurityMiddleware must be implemented in your project. It checks for incoming WebSocket requests and their protocol. In case, it is a TX Text Control WebSocket request (protocol: TXTextControl.Web), a given access token from the query string is checked. This very simple check is for demo purposes only. In real-world applications, the access token should be any identity token implemented through OAuth or any other security architecture.

public class WebSocketSecurityMiddleware
{
private RequestDelegate m_next;
// stored access token usually retrieved from any storage
// implemented thought 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"))
{
// retrieve access token from query string
var sAccess_token = context.Request.Query["access_token"];
// show case only: easy comparison of tokens
if (sAccess_token != access_token)
throw new UnauthorizedAccessException();
else
await m_next.Invoke(context);
}
else if (m_next != null)
{
await m_next.Invoke(context);
}
}
}
view raw api.cs hosted with ❤ by GitHub

In the Configure method of the Startup.cs file that configures the HTTP request pipeline, add the security middleware before the WebSocketMiddleware:

// attached the security middleware
app.UseMiddleware<WebSocketSecurityMiddleware>();
// attach the Text Control WebSocketHandler middleware
app.UseMiddleware<TXTextControl.Web.WebSocketMiddleware>();
view raw api.cs hosted with ❤ by GitHub

In the view, call the WebSocketURL property with an access token that will be used for the comparison in the security middleware:

@using TXTextControl.Web.MVC
@{
// use an access token (for example returned by OAuth)
var sAccessToken = "821e2f35-86e3-4917-a963-b0c4228d1315";
// build WebSocketURL including access token in query string
var sProtocol = (Context.Request.IsHttps) ? "wss://" : "ws://";
var sWebSocketURL = sProtocol + Context.Request.Host
+ "/TXWebSocket?access_token=" + sAccessToken;
}
@Html.TXTextControl().TextControl(settings =>
{
settings.WebSocketURL = sWebSocketURL; // pass built WebSocketURL
}).Render()
view raw test.cshtml hosted with ❤ by GitHub