How to JWT Authenticate with Angular to an ASP.NET Core C# API (OpenAPI/Swagger) using NSwag TypeScript
Tags: webdev, openapi, angular, dotnet
Published: 2021-03-30 14:15:32

This guide shows you how to use **[NSwag](https://github.com/RicoSuter/NSwag) to automatically add an OpenAPI specification** to an **ASP.NET Core REST-API**. It also serves the **Swagger UI** to the browser. You will use **NSwag Studio to generate a TypeScript client** and add the **strongly typed client** to your **Angular app**. Finally you **authenticate** to the backend via a **JWT bearer token**. 

*Workflow and involved components:*

![](https://cdn-images-1.medium.com/max/2000/1*oNZerE7P3U9l4gWgq7gb4w.png)

## Background and Structure of this Guide

When I wanted to create this kind of workflow I found descriptions showing some part of it. **This guide brings the parts together**.

**This guide focuses on the key aspects**. I link to other articles for details and download locations of the tools. I use [Visual Studio Community](https://visualstudio.microsoft.com/en/vs/community/) for ASP.NET Core 3.1 development.

The guide uses the **environment from my previous article** [“How to Sign-In with Google in Angular and use JWT based .NET Core API Authentication (RSA)”](https://dev.to/christianzink/how-to-sign-in-with-google-in-angular-and-use-jwt-based-net-core-api-authentication-rsa-1anl). You can **easily apply it to your own Angular project** with ASP.NET Core backend.

### Contents

1. Use NSwag in the ASP.NET Core Backend

2. Generate the TypeScript Client with NSwag Studio

3. Authenticate and Access the API from Angular

4. Final Thoughts and Outlook

------------

## 1. Use NSwag in the ASP.NET Core Backend

Use the Visual Studio package manager to **install the NSwag middleware** for the API project:
Install-Package NSwag.AspNetCore

**Edit Startup.cs** (lines 18, 34, 35) and **configure NSwag** to create the Swagger UI and OpenAPI specification:

{% gist https://gist.github.com/Chriz76/bc26c30c55fee03860c0bdc682ad33ac
%}

### Test the Result in the Browser

Start the API project and **open the Swagger UI** in your browser. In my project this is **[https://localhost:5002/swagger](https://localhost:5002/swagger)**:

![](https://cdn-images-1.medium.com/max/2000/1*xQDI2YrhF4tQ5n3uc3M1cw.png)

My API is a bit boring. Since it is only used to test the authentication, it has no parameters and no return values.

### Load the OpenAPI Specification

You can also **access the OpenAPI specification** (you will need the URL in the next step for NSwag Studio):

![](https://cdn-images-1.medium.com/max/2000/1*___uUORng1A4PmZZIJle9Q.png)

*Further reading for this step and the next step of this guide: [Using NSwag to Generate Angular Client for an ASP.NET Core 3 API](https://elanderson.net/2019/12/using-nswag-to-generate-angular-client-for-an-asp-net-core-3-api/) by Eric Anderson*

------------

## 2. Generate the TypeScript Client with NSwag Studio

[**Download NSwag Studio**](https://rsuter.com/Projects/NSwagStudio/installer.php) and install it.

**Start NSwag Studio** and **enter the “Specification URL”** from the previous step of this guide (e.q. “[https://localhost:5002/swagger/v1/swagger.json](https://localhost:5002/swagger/v1/swagger.json)”). **Select “TypeScript Client” as “Outputs”**:

![](https://cdn-images-1.medium.com/max/2710/1*gBIqDTkBrCLznTSeuh8Q2w.png)
> Make sure your API project from the previous step is running. NSwag Studio needs to access the OpenAPI sepcification.

**Select the “Angular” template** and **add “ApiBase” as “Base Class Name”**:

![](https://cdn-images-1.medium.com/max/2000/1*ORj4Z0Qfz6jeREnEVJB1bg.png)

**Select “transformOptions”** so later you can add the authentication header in the base class:

![](https://cdn-images-1.medium.com/max/2000/1*h3YvyO5FNpxFAXnvZ1oP5g.png)

**Create the file apibase.ts** (e.g. at “C:\dev\apibase.ts”). The code sets the authentication header. ApiBase is the base class of the file that NSwag will generate for you:

{% gist https://gist.github.com/Chriz76/d4474838f689435a2aa0b894850bf32b
%}

Then **configure apibase.ts as extension code file** in NSwag Studio:

![](https://cdn-images-1.medium.com/max/2000/1*HBhhJK2PO6rEcaAh3jvtSw.png)

Hit the **“Generate Outputs”** button and **copy the output**:

![](https://cdn-images-1.medium.com/max/2000/1*6p9z9mKPt-UJWjWRncO27Q.png)

------------

## 3. Authenticate and Access the API from Angular

**Create the file api.ts** in the app folder and **paste the output from the previous step** of this guide:

{% gist https://gist.github.com/Chriz76/dea1084599376c5e1d69abd49cc4c472 %}

**Use the generated code in app.component.ts to access the API**. Import the file (line 4) and call the API (line 24–26):

{% gist https://gist.github.com/Chriz76/c90fba3e53ee6ea3580d895f457e69dc %}

### Start the app

    c:\dev>ng serve

Login and use the debugger and logging in the chrome browser to verify that calling and authenticating at the backend is working:

![](https://cdn-images-1.medium.com/max/2496/1*JVH0R22k0Xyui1AdkHqEPA.png)

------------

## 4. Final Thoughts and Outlook

You used **NSwag to automatically create the OpenAPI/Swagger specification** for your API. Then **NSwag Studio created the TypeScript client** and you used it in Angular.

**The app is fully working!** But it is only a sample application and you will have to **clean up the code**, use Angular and .NET Core design patterns, error handling, etc. to use it in production. 

You need to handle logging off and timeouts. Maybe you want API paths that don’t require authentication, etc. You can **use the NSwag command line tool to automate the build pipeline**.

See also my **follow-up story**: [How to deploy the .NET Core API and Angular App as Microservices to Kubernetes using Ingress and develop local using Docker Desktop](https://dev.to/christianzink/how-to-build-an-asp-net-core-kubernetes-microservices-architecture-with-angular-on-local-docker-desktop-using-ingress-395n)

**Please contact me if you have any questions, ideas, or suggestions.**