Skip to content

Backend for frontend security using Angular Standalone (nx) and ASP.NET Core backend

License

Notifications You must be signed in to change notification settings

FabianGosebrink/bff-aspnetcore-angular

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

94 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

BFF security architecture using ASP.NET Core and nx Angular standalone

.NET and npm build Build and deploy to Azure Web App License

Setup Server

The ASP.NET Core project is setup to run in development and production. In production, it uses the Angular production build deployed to the wwwroot. In development, it uses MS YARP reverse proxy to forward requests.

Important

In production, the Angular nx project is built into the wwwroot of the .NET project.

BFF production

Configure the YARP reverse proxy to match the Angular nx URL. This is only required in development. I always use HTTPS in development and the port needs to match the Angular nx developement env.

 "UiDevServerUrl": "https://localhost:4201",
  "ReverseProxy": {
    "Routes": {
      "route1": {
        "ClusterId": "cluster1",
        "Match": {
          "Path": "{**catch-all}"
        }
      }
    },
    "Clusters": {
      "cluster1": {
        "HttpClient": {
          "SslProtocols": [
            "Tls12"
          ]
        },
        "Destinations": {
          "cluster1/destination1": {
            "Address": "https://localhost:4201/"
          }
        }
      }
    }
  }

Setup Angular nx

Add the certificates to the nx project for example in the /certs folder

Update the nx project.json file:

"serve": {
    "executor": "@angular-devkit/build-angular:dev-server",
    "options": {
    "browserTarget": "ui:build",
    "sslKey": "certs/dev_localhost.key",
    "sslCert": "certs/dev_localhost.pem",
    "port": 4201
},

Note

default Angular using port 4200, this needs to match the YARP reverse proxy settings for development.

Update the outputPath for the (nx build) to deploy the production paths to the wwwroot of the .NET project

 "build": {
      "executor": "@angular-devkit/build-angular:browser",
      "outputs": ["{options.outputPath}"],
      "options": {
        "outputPath": "../server/wwwroot",
        "index": "./src/index.html",
        "main": "./src/main.ts",
        "polyfills": ["zone.js"],
        "tsConfig": "./tsconfig.app.json",
        "assets": ["./src/favicon.ico", "./src/assets"],
        "styles": ["./src/styles.scss"],
        "scripts": []
      },

Note

When creating a new Angular nx project, it adds git files as well, delete these as this is not required.

Setup development

The development environment is setup to use the defualt tools for each of the tech stacks. Angular nx is used like recommended. I use Visual Studio code. A YARP reverse proxy is used to integrate the Angular development into the backend application.

BFF development

Note

Always run in HTTPS, both in development and production

nx server --ssl

Azure App Registration setup

The application(s) are deployed as one. This is an OpenID Connect confidential client with a user secret or a certification for client assertion.

Use the Web client type on setup.

BFF Azure registration

The OpenID Connect client is setup using Microsoft.Identity.Web. This implements the Microsoft Entra ID client. I have created downstream APIs using the OBO flow and a Microsoft Graph client. This could be replace with any OpenID Connect client and requires no changes in the frontend part of the solution.

var scopes = configuration.GetValue<string>("DownstreamApi:Scopes");
string[] initialScopes = scopes!.Split(' ');

services.AddMicrosoftIdentityWebAppAuthentication(configuration)
    .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
    .AddMicrosoftGraph("https://graph.microsoft.com/v1.0", initialScopes)
    .AddInMemoryTokenCaches();

services.AddControllersWithViews(options =>
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()));

services.AddRazorPages().AddMvcOptions(options =>
{
    //var policy = new AuthorizationPolicyBuilder()
    //    .RequireAuthenticatedUser()
    //    .Build();
    //options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();

App Service (linux plan) configuration

AzureAd__Instance               --your-value--
AzureAd__Domain                 --your-value--
AzureAd__TenantId               --your-value--
AzureAd__ClientId               --your-value--
AzureAd__CallbackPath           /signin-oidc
AzureAd__SignedOutCallbackPath  /signout-callback-oidc

The client secret or client certificate needs to be setup, see Microsoft Entra ID documentation.

github actions build

Github actions is used for the DevOps. The build pipeline builds both the .NET project and the Angular nx project using npm. The two projects are built in the same step because the UI project is built into the wwwroot of the server project.

name: .NET and npm build

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:

      - uses: actions/checkout@v3
      - name: Setup .NET
        uses: actions/setup-dotnet@v3
        with:
          dotnet-version: 7.0.x

      - name: Restore dependencies
        run: dotnet restore

      - name: npm setup
        working-directory: ui
        run: npm install

      - name: ui-nx-build
        working-directory: ui
        run: npm run build

      - name: Build
        run: dotnet build --no-restore
      - name: Test
        run: dotnet test --no-build --verbosity normal

github actions Azure deployment

The deployment pipeline builds both projects and deployes this to Azure using an Azure App Service. See azure-webapps-dotnet-core.yml

deployment test server: https://bff-angular-aspnetcore.azurewebsites.net

Credits and used libraries

  • NetEscapades.AspNetCore.SecurityHeaders
  • Yarp.ReverseProxy
  • Microsoft.Identity.Web
  • ASP.NET Core
  • Angular
  • Nx

Links

https://learn.microsoft.com/en-us/aspnet/core/introduction-to-aspnet-core

https://nx.dev/getting-started/intro

https://github.com/AzureAD/microsoft-identity-web

https://github.com/isolutionsag/aspnet-react-bff-proxy-example

About

Backend for frontend security using Angular Standalone (nx) and ASP.NET Core backend

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • C# 56.3%
  • TypeScript 26.8%
  • HTML 16.3%
  • Other 0.6%