ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ______ _ ___ _ β
β / ____/ /__ ____ _____ / | _______/ /_ β
β/ / / / _ \/ __ `/ __ \ / /| | / ___/ __ / β
β/ /___/ / __/ /_/ / / / // ___ |/ / / /_/ / β
β\____/_/\___/\__,_/_/ /_//_/ |_/_/ \__,_/ β
β β
β π§± CLEAN ARCHITECTURE & KEYCLOAK/ENTRA ID π§± β
β π Orchestrated by .NET 10 & Aspire 13 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
A production-ready, cloud-native template built on .NET 10 and Next.js 16 (React 19), orchestrated by Aspire 13 and ready to deploy to Azure Container Apps.
It features a C# Minimal API backend, a Next.js Admin Portal acting as a secure Backend-for-Frontend (BFF), pluggable authentication (Keycloak or Microsoft Entra ID), and a PostgreSQL database.
- π§± Clean Architecture β Layer boundaries enforced by automated architecture tests.
- β‘ .NET 10 Minimal API β Versioned endpoints (
/api/v1/...), the result pattern, and errors returned asProblemDetailswith status codes driven by the domain error type. - π§© CQRS via Source Generator β Powered by the Mediator source generator (not MediatR), with no runtime reflection cost. Logging and FluentValidation pipeline behaviours included.
- π Secure BFF Auth β The Next.js server handles sign-in (NextAuth.js) and forwards API calls through its own proxy route, attaching the access token server-side. Tokens never reach the browser, and the .NET API is never exposed publicly.
- π Pluggable Identity β Keycloak runs locally with its realm auto-imported; production uses Microsoft Entra ID by default, or Keycloak if you turn it on.
- π Role-Based Authorization β
Viewer,EditorandAdminpolicies built on theview,create,editanddeleteroles. - π Next.js 16 Admin Panel β Tailwind CSS 4, i18n in English, Persian and Arabic (RTL), and responsive layouts.
- β‘ Orval-Generated Client β TypeScript types and TanStack Query hooks generated from the backend OpenAPI spec.
- π PostgreSQL & EF Core 10 β Change-tracked auditing, domain events dispatched inside the save transaction, and a dedicated migrator project (
DbMigrator). - π§ Brevo Email Service β Transactional email client that falls back to a null service when no API key is configured.
- βοΈ Aspire Orchestration β One command starts the whole stack locally;
aspire deployprovisions and deploys it to Azure. - π Observability β Serilog and OpenTelemetry feed the Aspire dashboard locally and Application Insights in Azure.
- π‘οΈ HTTP Resilience β Standard retry, timeout and circuit-breaker handlers on every
HttpClient, configured once in Service Defaults. - π Scalar API Docs β Interactive API reference with OAuth sign-in through Keycloak (Development only).
Arrows point from a layer to the layer it depends on.
ββββββββββββββββββββββββββββββββ
β Presentation (API) β composition root
ββββββββββββββββββββββββββββββββ
β β
βΌ βΌ
βββββββββββββββ ββββββββββββββββββββββββββββββββ
β Application βββββ Infrastructure / Persistence β
βββββββββββββββ ββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββ
β Domain β
βββββββββββββββ
| Layer | Responsibility & Details |
|---|---|
| π Domain | Aggregates, value objects (Genre), domain events and validation rules. Its only package is DomainValidation.NET; nothing from persistence, messaging or the web is allowed in. |
| βοΈ Application | CQRS commands/queries returning Result<T>, FluentValidation validators, logging/validation pipeline, and domain-event notification handlers. |
| π‘οΈ Infrastructure | Brevo email service, current-user access, and the authorization policies. |
| π Persistence | EF Core 10 DbContext, auditing and domain-event interceptors, and migrations for PostgreSQL. |
| ποΈ DbMigrator | Applies pending migrations before the API starts. |
| π΅ Presentation (API) | Minimal API endpoints, versioned route groups, Result β HTTP response mapping, and Scalar docs. |
| π£ Presentation (Admin) | Next.js admin dashboard: NextAuth.js BFF, API proxy route, and Orval-generated query hooks. |
| π§° ServiceDefaults | OpenTelemetry, health checks, service discovery, and HTTP resilience shared by every .NET service. |
| π Aspire AppHost | Orchestrates everything locally and defines the Azure resources for deployment. |
- π¦ .NET 10 SDK
- π Aspire CLI β
curl -sSL https://aspire.dev/install.sh | bash - π³ Docker Desktop β runs the PostgreSQL, PgAdmin and Keycloak containers
- π’ Node.js 22.13+ & pnpm 11 β
corepack enablepicks up the version pinned inpackage.json - π A trusted HTTPS development certificate β
dotnet dev-certs https --trust - π©οΈ Optional, for deployment: an Azure subscription and the Azure CLI, signed in with
az login
# 1. Clone the repository
git clone https://github.com/iPazooki/CleanArchitecture.git
cd CleanArchitecture
# 2. Restore .NET dependencies
dotnet restore
# 3. Install admin portal node modules
cd CleanArchitecture.Presentation/admin
pnpm install
# 4. Create .env.local for the admin portal (see "Admin Portal Config" below)
# 5. Run the entire stack with Aspire from the repository root
cd ../..
aspire runaspire run uses aspire.config.json to find the AppHost. Running dotnet run --project CleanArchitecture.Aspire/CleanArchitecture.AppHost does the same thing.
Open the Aspire Dashboard link printed in your terminal to monitor every service:
| Service | Local address |
|---|---|
| π£ Admin Portal (Next.js) | http://localhost:65499 |
| π΅ API | https://localhost:7281 Β· http://localhost:5049 |
| π Scalar API reference | https://localhost:7281/scalar |
π Keycloak (realm clean-api) |
https://localhost:8180 β admin console login admin / admin |
| π PostgreSQL + PgAdmin | Linked from the Aspire dashboard |
| ποΈ DbMigrator | Runs once, before the API starts |
The imported realm has no users. Before you sign in to the admin portal:
- Open the Keycloak admin console at https://localhost:8180 and switch to the
clean-apirealm. - Create a user and set a (non-temporary) password.
- Under Role mapping, assign the realm roles the user needs:
| Action | Policy | Roles required |
|---|---|---|
| List / view books | Viewer |
any one of view, create, edit, delete |
| Create / edit books | Editor |
all of view, create, edit |
| Delete books | Admin |
all four roles |
Note
Keycloak keeps its data in a persistent volume, and the realm import skips existing realms. Changes to Realms/realm-export.json only take effect after you remove the Keycloak data volume.
The Development AppHost always runs Keycloak and imports the clean-api realm. It has two clients: mrpanel (the admin portal) and scalar (the API reference). The API's appsettings.Development.json already points at it, so the API needs no extra setup.
The AppHost generates the mrpanel client secret once, saves it in the AppHost's user secrets, and injects it into Keycloak and the admin portal as KEYCLOAK_CLIENT_SECRET.
Create CleanArchitecture.Presentation/admin/.env.local:
API_BASE_URL=http://localhost:5049/
NEXTAUTH_URL=http://localhost:65499
# Generate a secret: node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
NEXTAUTH_SECRET=your-random-32-byte-base64-secret
AUTH_PROVIDER=Keycloak # "Keycloak" or "Entra" (case-insensitive)
KEYCLOAK_CLIENT_ID=mrpanel
KEYCLOAK_ISSUER=https://localhost:8180/realms/clean-api
KEYCLOAK_SCOPES=openid profile email permissions
# KEYCLOAK_CLIENT_SECRET is injected by the AppHost; a value already in the
# environment takes precedence over .env.local.
# Only when AUTH_PROVIDER=Entra:
# ENTRA_CLIENT_ID=<Your-Entra-Client-ID>
# ENTRA_CLIENT_SECRET=<Your-Entra-Client-Secret>
# ENTRA_TENANT_ID=<Your-Entra-Tenant-ID>
# ENTRA_SCOPES=openid profile email offline_access api://<Your-Audience-ID>/permissions
# ENTRA_OPENID_CONNECT=https://<Your-Domain>.ciamlogin.com/<Your-Tenant-ID>/v2.0/.well-known/openid-configurationThe admin validates these variables at startup. Whichever provider you select, its variables become required.
The Production AppHost reads two settings, from CleanArchitecture.Aspire/CleanArchitecture.AppHost/appsettings.json or environment variables:
| Setting | Default | Effect |
|---|---|---|
UseKeycloak |
false |
false β Microsoft Entra ID; true β a Keycloak container app backed by the PostgreSQL server |
UseBrevo |
false |
true β wires the Brevo API key and sender into the API |
The AppHost sets Authentication__Provider on the API and AUTH_PROVIDER on the admin portal to match. Each mode needs these AppHost parameters, which aspire deploy prompts for:
- Always:
nextAuthSecret,PostgresUsername,PostgresPassword - Entra ID:
EntraTenantId,EntraAPIInstance,EntraAPIPrimaryDomain,EntraAPIClientId,EntraAPIAudienceId,EntraAdminClientId,EntraAdminClientSecret,EntraAdminScope,EntraAdminOpenIdURL - Keycloak:
keycloakClientId,keycloakClientSecret,keycloakRealm,keycloakAdminUsername,keycloakAdminPassword,keycloakDbUsername,keycloakDbPassword - Brevo:
brevoApiKey,brevoSenderName,brevoSenderEmail
Secrets are stored in Azure Key Vault. Entra app roles (or realm roles in a production Keycloak) must use the same names as Security/Roles.cs: view, create, edit and delete. Production Keycloak doesn't import the realm, so you configure it yourself.
The UI lives in CleanArchitecture.Presentation/admin. Browser code calls the app's own proxy route (src/app/api/v1/[...path]), which strips any client-supplied credentials, attaches the user's access token, and forwards the request to API_BASE_URL.
# Start Next.js development server manually
pnpm dev
# Produce a production build
pnpm build
# Run linting with warnings treated as errors
pnpm lint
# Regenerate API client and TanStack Query hooks from the OpenAPI spec
pnpm generateImportant
The TypeScript API client and hooks in src/lib/api/ are generated by Orval from http://localhost:5049/openapi/v1.json. Do not edit these files by hand. Run pnpm generate after changing endpoints or DTOs. The API must be running in Development, the only environment where OpenAPI and Scalar are mapped.
Database operations use EF Core 10 with Npgsql targeting PostgreSQL. The CleanArchitecture.DbMigrator project applies pending migrations:
- Locally: the migrator runs on every
aspire run, and the API waits for it to finish. - In Azure: it is deployed as a manually triggered Container Apps Job (
db-migrator). Start it after a deployment that adds migrations:az containerapp job start --name db-migrator --resource-group <your-resource-group>
Requires the EF Core CLI (dotnet tool install --global dotnet-ef):
dotnet ef migrations add <MigrationName> \
--project CleanArchitecture.Infrastructure.Persistence \
--startup-project CleanArchitecture.Presentation/APIThe template integrates the Brevo transactional email API.
- Fallback behavior: If
Brevo:ApiKeyis not configured, the application usesNullEmailService, so local runs work without a key. - Local secret:
dotnet user-secrets set "Brevo:ApiKey" "<your-key>" --project CleanArchitecture.Presentation/API
- Production: set
UseBrevototruein the AppHost; the key flows from thebrevoApiKeyparameter into Key Vault.
Run all tests from the repository root:
dotnet test --configuration ReleaseAll tests run in-process, so neither Docker nor the Aspire host needs to be running.
- Domain Unit Tests β Aggregate invariants, domain events, and the
Genrevalue object. - Application Unit Tests β Persistence behaviour such as the auditable-entity interceptor.
- Architecture Tests β Enforce the layer dependency rules: Domain depends on nothing, Application only on Domain, and Infrastructure/Persistence only on Application. A forbidden dependency fails the test run.
The tests use xUnit v3 on Microsoft.Testing.Platform, so filter with MTP flags instead of --filter:
dotnet test --project Tests/Domain.UnitTests/Domain.UnitTests.csproj --filter-class "*BookTests"
dotnet test --project Tests/Domain.UnitTests/Domain.UnitTests.csproj --filter-method "*Create*"Directory.Build.props turns on nullable reference types, TreatWarningsAsErrors, AnalysisMode=All and SonarAnalyzer for every project, so an analyzer warning breaks the build. CI (.github/workflows/dotnet.yml) builds and tests in Release mode on every push and pull request to main or aspire.
The Production AppHost deploys the entire stack to Azure, provisioning:
- π’ Azure Container Apps β The admin portal (public), the API (internal ingress only), the DbMigrator job, and, when
UseKeycloakis on, Keycloak. - π Azure Database for PostgreSQL (Flexible Server) β Burstable
Standard_B1mstier, with 7-day backups. - π Azure Key Vault β Database, auth provider, NextAuth and Brevo secrets.
- π Application Insights β Logs, traces and metrics.
# Provision Azure resources and deploy the code (prompts for missing settings and parameters)
aspire deploy
# Optional: generate the deployment artifacts without deploying
aspire publishThen start the db-migrator job (see Database & Migrations). The repository also includes an azure.yaml, so azd up works too.
Contributions are welcome! Please open an issue first to discuss proposed changes.
β If you find this template helpful, please star the repo β it helps others find it!
This project is licensed under the MIT License - free for personal and commercial use.