# Implementing a Security Middleware for Angular Document Editor Applications in C#

> This article shows how to implement a security middleware for Angular Document Editor applications using ASP.NET Core. The middleware is used to validate access tokens and to protect the Document Editor API.

- **Author:** Bjoern Meyer
- **Published:** 2024-10-14
- **Modified:** 2026-07-17
- **Description:** This article shows how to implement a security middleware for Angular Document Editor applications using ASP.NET Core. The middleware is used to validate access tokens and to protect the Document Editor API.
- **4 min read** (611 words)
- **Tags:**
  - ASP.NET
  - Angular
  - Security
  - Access Token
- **Web URL:** https://www.textcontrol.com/blog/2024/10/14/implementing-a-security-middleware-for-angular-document-editor-applications/
- **LLMs URL:** https://www.textcontrol.com/blog/2024/10/14/implementing-a-security-middleware-for-angular-document-editor-applications/llms.txt
- **LLMs-Full URL:** https://www.textcontrol.com/blog/2024/10/14/implementing-a-security-middleware-for-angular-document-editor-applications/llms-full.txt
- **GitHub Repository:** https://github.com/TextControl/TXTextControl.Angular.Security

---

When building a backend for the TX Text Control Document Editor and Document Viewer, the TX Text Control NuGet packages implement the necessary endpoints and handlers to communicate between the client-side libraries and the backend.

Middleware that checks for an access token is recommended to secure these endpoints. This demo implementation does not create and store access tokens, but illustrates how incoming requests can be checked for an access token. Typically, your actual authorization layer, such as OAuth, creates the access tokens.

The request flow with integrated custom security middleware is illustrated in the following diagram.

![TX Text Control Security Middleware](https://s1-www.textcontrol.com/assets/dist/blog/2024/10/14/a/assets/middleware.webp "TX Text Control Security Middleware")

When the client-side Angular package requests resources from the backend, the implemented custom security middleware intercepts the request and validates a security access token sent with the request.

### Security Middleware

The security middleware is implemented in the `TXSecurityMiddleware` class. It basically checks a security token passed as a query string against a stored access token. To illustrate this workflow, the access token is simply hard-coded into the application settings.

```
namespace TXTextControl
{
    public class TXSecurityMiddleware
    {

        private IConfiguration configuration;

        public TXSecurityMiddleware(RequestDelegate next, IConfiguration configuration)
        {
            m_next = next;
            this.configuration = configuration;
        }

        private RequestDelegate m_next;

        public async Task Invoke(HttpContext context)
        {

            var access_token = this.configuration.GetSection("Security")["AccessToken"];

            // Check if the request is a TX Text Control request
            if (context.WebSockets.IsWebSocketRequest &&
              context.WebSockets.WebSocketRequestedProtocols.Contains("TXTextControl.Web") ||
              (context.Request.Query.ContainsKey("access_token") &&
              context.GetEndpoint()?.DisplayName?.Contains("TXTextControl.Web.MVC.DocumentViewer") == true))
            {
                // Retrieve access token from the query string
                var accessToken = context.Request.Query["access_token"];

                // Showcase only: Easy comparison of tokens
                if (accessToken != access_token)
                {
                    throw new UnauthorizedAccessException();
                }
                else
                {
                    await m_next.Invoke(context);
                }
            }
            else if (m_next != null)
            {
                await m_next.Invoke(context);
            }
        }

    }

}
```

The middleware is registered in the *Program.cs* request pipeline.

```
app.UseWebSockets();

// Add the TX Security Middleware to the request pipeline
app.UseMiddleware<TXTextControl.TXSecurityMiddleware>();

// TX Text Control specific middleware
app.UseTXWebSocketMiddleware();
```

The backend also implements an HttpGet method that returns an access token to simulate a common token workflow such as OAuth, where an access token is exchanged for a user id and user secret. In this sample workflow, the method simply returns a valid access token.

```
[ApiController]
 [Route("[controller]")]
 public class TXSecurityTokenController : ControllerBase
 {
     private IConfiguration configuration;

     public TXSecurityTokenController(IConfiguration configuration)
     {
         this.configuration = configuration;
     }

     [HttpGet]
     public SecurityToken Get()
     {
         return new SecurityToken() { AccessToken = this.configuration.GetSection("Security")["AccessToken"] };
     }
 }
```

### Requesting Resources

When the client-side Angular application requests resources from the backend, the security token is passed as a query string. The following code shows where the Angular application retrieves the access token from the backend endpoint.

```
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

interface SecurityToken {
  accessToken: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent implements OnInit {
  public securityToken: SecurityToken | undefined;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.getTokens();
  }

  getTokens() {
    this.http.get<SecurityToken>('/txsecuritytoken').subscribe(
      (result) => {
        this.securityToken = result;
      },
      (error) => {
        console.error(error);
      }
    );
  }

  title = 'tx-security.client';
```

This retrieved access token is then used as the query string in the *webSocketURL* property.

```
<h1 id="tableLabel">Security Token Sample</h1>

<p>
  This component demonstrates how to retrieve a security token from the server and how to use it.
</p>

<p *ngIf="!securityToken"><em>Loading... Please refresh once the ASP.NET backend has started. See <a href="https://aka.ms/jspsintegrationangular">https://aka.ms/jspsintegrationangular</a> for more details.</em></p>

<table *ngIf="securityToken">
  <thead>
    <tr>
      <th>AccessToken retrieved:</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      {{ securityToken.accessToken }}
    </tr>
  </tbody>
</table>

<div *ngIf="securityToken">
  <tx-document-editor width="1000px"
                      height="500px"
                      webSocketURL="wss://localhost:7289/TXWebSocket?access_token={{ securityToken.accessToken }}">
  </tx-document-editor>
</div>
```

After the token is validated, the editor is initialized.

![TX Text Control Security Middleware](https://s1-www.textcontrol.com/assets/dist/blog/2024/10/14/a/assets/editor.webp "TX Text Control Security Middleware")

Download the complete project from GitHub and test it on your own.

---

## 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

- [DS Server: Authorizing Angular Client Components](https://www.textcontrol.com/blog/2021/03/08/ds-server-authorizing-angular-client-components/llms.txt)
- [Building an ASP.NET Core Backend (Linux and Windows) for the Document Editor and Viewer](https://www.textcontrol.com/blog/2025/03/26/building-an-asp-net-core-backend-for-the-document-editor-and-viewer/llms.txt)
- [Impressions from .NET Developer Conference DDC 2024](https://www.textcontrol.com/blog/2024/11/28/impressions-from-net-developer-conference-ddc-2024/llms.txt)
- [Back from Florida: Impressions from VSLive! Orlando 2024](https://www.textcontrol.com/blog/2024/11/21/back-from-florida-impressions-from-vslive-orlando-2024/llms.txt)
- [Exporting Password Protected Documents to PDF in .NET C#](https://www.textcontrol.com/blog/2024/10/28/exporting-password-protected-documents-to-pdf-in-net-c-sharp/llms.txt)
- [Meet Text Control at DDC .NET Developer Conference 2024](https://www.textcontrol.com/blog/2024/10/07/meet-text-control-at-ddc-net-developer-conference-2024/llms.txt)
- [Visit Text Control at VSLive! in Orlando, Florida](https://www.textcontrol.com/blog/2024/10/01/visit-tx-text-control-at-vslive-in-orlando-florida/llms.txt)
- [Creating Advanced Tables in PDF and DOCX Documents with C#](https://www.textcontrol.com/blog/2024/09/30/creating-advanced-tables-in-pdf-and-docx-documents-with-csharp/llms.txt)
- [Back in the Pocono Mountains: Meet Text Control at TechBash 2024](https://www.textcontrol.com/blog/2024/09/24/back-in-the-pocono-mountains-meet-text-control-at-techbash-2024/llms.txt)
- [Back from Copenhagen Developers Festival 2024](https://www.textcontrol.com/blog/2024/09/05/back-from-copenhagen-developers-festival-2024/llms.txt)
- [Using the Document Editor in SPA Applications using the removeFromDom Method](https://www.textcontrol.com/blog/2024/09/02/using-the-document-editor-in-spa-applications-using-the-removefromdom-method/llms.txt)
- [Video Tutorial: Creating a MailMerge Template and JSON Data Structure](https://www.textcontrol.com/blog/2024/08/16/video-tutorial-creating-a-mailmerge-template-and-json-data-structure/llms.txt)
- [Observe When the Reporting Preview Tab is Active Using MutationObserver](https://www.textcontrol.com/blog/2024/07/23/observe-when-the-reporting-preview-tab-is-active-using-mutationobserver/llms.txt)
- [Mail Merge: The Pre-Shaped Data Concept Explained](https://www.textcontrol.com/blog/2024/05/30/mail-merge-the-pre-shaped-data-concept-explained/llms.txt)
- [Meet Text Control at NDC Oslo 2024](https://www.textcontrol.com/blog/2024/05/28/meet-text-control-at-ndc-oslo-2024/llms.txt)
- [Form Field Compatibility: Work with AcroForms, Legacy MS Word Forms, and Content Controls](https://www.textcontrol.com/blog/2024/04/04/form-fields-working-with-acroforms-legacy-ms-word-forms-and-content-controls/llms.txt)
- [Comments JavaScript API: Useful Tips and Tricks](https://www.textcontrol.com/blog/2024/04/01/comments-javascript-api-useful-tips-and-tricks/llms.txt)
- [Integrating Document Lifecycle Management with ASP.NET Core and C#](https://www.textcontrol.com/blog/2024/03/29/integrating-document-lifecycle-management-with-asp-net-core-and-c-sharp/llms.txt)
- [Adding a Security Middleware to ASP.NET Core Web Applications to Protect TX Text Control Document Editor and Document Viewer Endpoints](https://www.textcontrol.com/blog/2024/03/18/adding-a-security-middleware-to-asp-net-core-web-applications-to-protect-tx-text-control-document-editor-and-document-viewer-endpoints/llms.txt)
- [Building an ASP.NET Core Backend Application to Host the Document Editor and Document Viewer](https://www.textcontrol.com/blog/2024/03/14/building-an-asp-net-core-backend-application-to-host-the-document-editor-and-document-viewer/llms.txt)
- [Customizing Electronic Signature Fonts for Typed Signatures in Angular and ASP.NET Core](https://www.textcontrol.com/blog/2024/03/11/customizing-electronic-signature-fonts-for-typed-signatures-in-angular-and-asp-net-core/llms.txt)
- [How to Secure your PDF Documents with ASP.NET Core C#](https://www.textcontrol.com/blog/2023/11/13/how-to-secure-your-pdf-documents-with-aspnet-core-csharp/llms.txt)
- [E-Sign: Validating Signature Hashes Generated from Vector Data in ASP.NET Core C#](https://www.textcontrol.com/blog/2023/10/30/esign-validating-signature-hashes-generated-from-vector-data-in-aspnet-core-csharp/llms.txt)
- [View and Edit MS Word DOCX Documents in Angular](https://www.textcontrol.com/blog/2023/10/26/view-and-edit-ms-word-docx-documents-in-angular/llms.txt)
- [Impressions from Web Developer Conference WDC 2023 in Hamburg, Germany](https://www.textcontrol.com/blog/2023/09/21/impressions-from-web-developer-conference-wdc-2023-in-hamburg-germany/llms.txt)
