Track E · Tutorial 2

ASP.NET Security, Testing & Azure Deployment

Chapter 28 · Backend Specialization
~3 hours Advanced JWT · xUnit · Azure · Swagger

Overview

This tutorial secures your ASP.NET Core API with JWT, adds comprehensive testing with xUnit and Moq, deploys to Azure App Service, and documents your API with Swagger/OpenAPI.

Why this matters: Security, testing, and cloud deployment are essential for professional applications. Azure provides a seamless deployment experience for .NET.

1. JWT Authentication

Add JWT authentication using Microsoft.AspNetCore.Authentication.JwtBearer.

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
// Program.cs builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidIssuer = builder.Configuration["Jwt:Issuer"], ValidAudience = builder.Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])) }; }); builder.Services.AddAuthorization(); app.UseAuthentication(); app.UseAuthorization();
// AuthController.cs [ApiController] [Route("api/[controller]")] public class AuthController : ControllerBase { [HttpPost("login")] public IActionResult Login([FromBody] LoginRequest request) { // Validate credentials var token = GenerateJwtToken(request.Username); return Ok(new { token }); } private string GenerateJwtToken(string username) { var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(ClaimTypes.Name, username) }; var token = new JwtSecurityToken( issuer: _config["Jwt:Issuer"], audience: _config["Jwt:Audience"], claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: credentials); return new JwtSecurityTokenHandler().WriteToken(token); } }
// Protect endpoints with [Authorize] [Authorize] [ApiController] [Route("api/[controller]")] public class ProductsController : ControllerBase { ... }

2. Testing with xUnit & Moq

Use xUnit for testing and Moq for mocking dependencies.

dotnet add package xunit dotnet add package Moq dotnet add package Microsoft.AspNetCore.Mvc.Testing
// ProductServiceTests.cs public class ProductServiceTests { [Fact] public void GetProducts_ShouldReturnList() { // Arrange var mockRepo = new Mock(); mockRepo.Setup(r => r.GetAll()).Returns(new List()); var service = new ProductService(mockRepo.Object); // Act var result = service.GetAll(); // Assert Assert.NotNull(result); } }
// Integration test with WebApplicationFactory public class ProductApiTests : IClassFixture> { private readonly HttpClient _client; public ProductApiTests(WebApplicationFactory factory) { _client = factory.CreateClient(); } [Fact] public async Task GetProducts_ShouldReturnOk() { var response = await _client.GetAsync("/api/products"); Assert.Equal(HttpStatusCode.OK, response.StatusCode); } }

3. Azure Deployment

Deploy to Azure App Service

# Publish the application dotnet publish -c Release -o ./publish # Deploy using Azure CLI az webapp deployment source config-zip --resource-group myResourceGroup --name myAppService --src ./publish.zip

Set environment variables in Azure (Connection Strings, JWT settings).

Azure DevOps CI/CD

Use Azure Pipelines to automate build, test, and deployment.

4. Swagger/OpenAPI

Document your API with Swagger.

dotnet add package Swashbuckle.AspNetCore
// Program.cs builder.Services.AddSwaggerGen(); // ... app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"));

Access Swagger UI at /swagger.

Quiz

Question 1

Which package is used for JWT authentication in ASP.NET Core?

  • Microsoft.AspNetCore.Authentication.Jwt
  • Microsoft.AspNetCore.Authentication.JwtBearer
  • Microsoft.AspNetCore.Jwt
  • System.IdentityModel.Tokens.Jwt
Show answer
B. Microsoft.AspNetCore.Authentication.JwtBearer.

Question 2

Which testing framework is recommended for .NET Core?

  • NUnit
  • xUnit
  • MSTest
  • All of the above
Show answer
D. All of the above (but xUnit is the most popular with .NET Core).

Question 3

What is the URL to access Swagger UI by default?

  • /swagger
  • /api/docs
  • /openapi
  • /docs
Show answer
A. /swagger.

Exercises

Exercise 1

Add JWT authentication to the Inventory API from Tutorial 1. Protect all write endpoints.

Sample answer
  • Add JWT packages and configure authentication in Program.cs.
  • Create AuthController with Login endpoint.
  • Add [Authorize] attribute to POST, PUT, DELETE endpoints.
  • Test with Postman using Bearer token.

Exercise 2

Write an integration test for the GET /api/products endpoint that validates the response format.

Sample answer
[Fact] public async Task GetProducts_ShouldReturnValidFormat() { var response = await _client.GetAsync("/api/products"); response.EnsureSuccessStatusCode(); var content = await response.Content.ReadAsStringAsync(); var products = JsonSerializer.Deserialize>(content); Assert.NotNull(products); }

Homework

Homework 1

Extend the Inventory API with JWT authentication and Azure deployment. Deploy the API to Azure App Service and document it with Swagger.

Sample outline
  • Add JWT authentication with custom user validation.
  • Add Swagger and configure it to work with JWT.
  • Publish to Azure App Service using Azure CLI or DevOps.
  • Test the live API with Swagger UI.

Mini‑Project

E‑Commerce API with Azure

Build a complete e‑commerce API with:

  • Product, Category, Order, User models
  • JWT authentication
  • Unit and integration tests (xUnit + Moq)
  • Swagger documentation
  • Deployed to Azure App Service
  • Azure SQL Database
Sample outline
  • Models: User, Product, Category, Order, OrderItem
  • DbContext: Configure relationships
  • Auth: JWT with custom user service
  • Tests: Service tests (Moq) and integration tests (WebApplicationFactory)
  • Azure: App Service + Azure SQL
  • CI/CD: Azure DevOps Pipeline

Tutorial Summary

You secured ASP.NET Core APIs with JWT, wrote comprehensive tests with xUnit and Moq, deployed to Azure App Service, and documented your API with Swagger. You now have a complete, production‑ready workflow for .NET backend development in the cloud.

Key takeaway: ASP.NET Core, combined with Azure, provides a powerful platform for building and deploying secure, scalable APIs. The tooling and ecosystem are world‑class.