Giter Site home page Giter Site logo

damienbod / bff-aspnetcore-angular Goto Github PK

View Code? Open in Web Editor NEW
86.0 7.0 15.0 1.36 MB

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

Home Page: https://damienbod.com/2023/09/11/implement-a-secure-web-application-using-nx-standalone-angular-and-an-asp-net-core-server/

License: Apache License 2.0

TypeScript 23.68% JavaScript 0.28% HTML 16.37% SCSS 0.25% C# 59.41%
angular aspnetcore bff cookie csp csrf nx yarp azuread entra

bff-aspnetcore-angular's Introduction

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.

Important

In a real Angular project, the additional dev routes need to be added so that the dev refresh works!

 "UiDevServerUrl": "https://localhost:4201",
 "ReverseProxy": {
    "Routes": {
      "assets": {
        "ClusterId": "cluster1",
        "Match": {
          "Path": "assets/{**catch-all}"
        }
      },
      "routealljs": {
        "ClusterId": "cluster1",
        "Match": {
          "Path": "{nomatterwhat}.js"
        }
      },
      "routeallcss": {
        "ClusterId": "cluster1",
        "Match": {
          "Path": "{nomatterwhat}.css"
        }
      },
      "webpacklazyloadingsources": {
        "ClusterId": "cluster1",
        "Match": {
          "Path": "/src_{nomatterwhat}_ts.js"
        }
      },
      "signalr": {
        "ClusterId": "cluster1",
        "Match": {
          "Path": "/ng-cli-ws"
        }
      },
      "webpacknodesrcmap": {
        "ClusterId": "cluster1",
        "Match": {
          "Path": "/{nomatterwhat}.js.map"
        }
      }
    },
    "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

The default Angular setup uses 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 default 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 replaced 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, "MicrosoftEntraID")
    .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();

Add the Azure App registration settings to the appsettings.Development.json and the ClientSecret to the user secrets.

"MicrosoftEntraID": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com]",
    "TenantId": "[Enter 'common', or 'organizations' or the Tenant Id (Obtained from the Azure portal. Select 'Endpoints' from the 'App registrations' blade and use the GUID in any of the URLs), e.g. da41245a5-11b3-996c-00a8-4d99re19f292]",
    "ClientId": "[Enter the Client Id (Application ID obtained from the Azure portal), e.g. ba74781c2-53c2-442a-97c2-3d60re42f403]",
    "ClientSecret": "[Copy the client secret added to the app from the Azure portal]",
    "ClientCertificates": [
    ],
    // the following is required to handle Continuous Access Evaluation challenges
    "ClientCapabilities": [ "cp1" ],
    "CallbackPath": "/signin-oidc"
},

App Service (linux plan) configuration

MicrosoftEntraID__Instance               --your-value--
MicrosoftEntraID__Domain                 --your-value--
MicrosoftEntraID__TenantId               --your-value--
MicrosoftEntraID__ClientId               --your-value--
MicrosoftEntraID__CallbackPath           /signin-oidc
MicrosoftEntraID__SignedOutCallbackPath  /signout-callback-oidc

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

Debugging

Start the Angular project from the ui folder

nx serve --ssl

Start the ASP.NET Core project from the server folder

dotnet run

Or just open Visual Studio and run the solution.

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: 8.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

https://github.com/damienbod/bff-auth0-aspnetcore-angular

https://github.com/damienbod/bff-openiddict-aspnetcore-angular

https://github.com/damienbod/bff-azureadb2c-aspnetcore-angular

https://github.com/damienbod/bff-aspnetcore-vuejs

https://github.com/damienbod/bff-MicrosoftEntraExternalID-aspnetcore-angular

bff-aspnetcore-angular's People

Contributors

damienbod avatar fabiangosebrink avatar q-sharp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

bff-aspnetcore-angular's Issues

Improve refresh SPA part when working with the dev proxy

"reactrefresh": {
        "ClusterId": "cluster1",
        "Match": {
          "Path": "@react-refresh"
        }
      },
      "vite": {
        "ClusterId": "cluster1",
        "Match": {
          "Path": "@vite/{**catch-all}"
        }
      },
      "sourcefiles": {
        "ClusterId": "cluster1",
        "Match": {
          "Path": "src/{**catch-all}"
        }
      },
      "nodemodules": {
        "ClusterId": "cluster1",
        "Match": {
          "Path": "node_modules/{**catch-all}"
        }
      },
      "yarncachedfiles": {
        "ClusterId": "cluster1",
        "Match": {
          "Path": ".yarn/{**catch-all}"
        }
      },
      "wellknown": {
        "ClusterId": "cluster1",
        "Match": {
          "Path": "well-known/{**catch-all}"
        }
      },
      "favicon": {
        "ClusterId": "cluster1",
        "Match": {
          "Path": "{**catch-all}"
          "Path": "favicon.ico"
        }
      }

awesome @rufer7 thanks, will adapt this for the Angular and Vue version

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.