{"id":13591938,"url":"https://github.com/damienbod/bff-aspnetcore-angular","last_synced_at":"2025-04-05T11:08:23.409Z","repository":{"id":192740199,"uuid":"685647793","full_name":"damienbod/bff-aspnetcore-angular","owner":"damienbod","description":"Backend for frontend security using Angular Standalone (nx) and ASP.NET Core backend","archived":false,"fork":false,"pushed_at":"2025-01-28T20:38:28.000Z","size":1658,"stargazers_count":121,"open_issues_count":10,"forks_count":19,"subscribers_count":9,"default_branch":"main","last_synced_at":"2025-03-04T13:46:18.549Z","etag":null,"topics":["angular","aspnetcore","azuread","bff","cookie","csp","csrf","entra","microsoftentraid","microsoftidentity","msal","nx","yarp"],"latest_commit_sha":null,"homepage":"https://damienbod.com/2023/09/11/implement-a-secure-web-application-using-nx-standalone-angular-and-an-asp-net-core-server/","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/damienbod.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-08-31T17:35:26.000Z","updated_at":"2025-03-02T10:57:43.000Z","dependencies_parsed_at":null,"dependency_job_id":"7821ed92-56b0-4a24-a72c-349b2adc4b1b","html_url":"https://github.com/damienbod/bff-aspnetcore-angular","commit_stats":{"total_commits":149,"total_committers":3,"mean_commits":"49.666666666666664","dds":0.02684563758389258,"last_synced_commit":"81f03a944faf5acb5e4408fbcd6d86f5d3e13aa2"},"previous_names":["damienbod/bff-aspnetcore-angular"],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/damienbod%2Fbff-aspnetcore-angular","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/damienbod%2Fbff-aspnetcore-angular/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/damienbod%2Fbff-aspnetcore-angular/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/damienbod%2Fbff-aspnetcore-angular/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/damienbod","download_url":"https://codeload.github.com/damienbod/bff-aspnetcore-angular/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247325693,"owners_count":20920714,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["angular","aspnetcore","azuread","bff","cookie","csp","csrf","entra","microsoftentraid","microsoftidentity","msal","nx","yarp"],"created_at":"2024-08-01T16:01:03.874Z","updated_at":"2025-04-05T11:08:23.374Z","avatar_url":"https://github.com/damienbod.png","language":"C#","readme":"# BFF security architecture using ASP.NET Core and nx Angular standalone\n\n[![.NET and npm build](https://github.com/damienbod/bff-aspnetcore-angular/actions/workflows/dotnet.yml/badge.svg)](https://github.com/damienbod/bff-aspnetcore-angular/actions/workflows/dotnet.yml) [![Build and deploy to Azure Web App](https://github.com/damienbod/bff-aspnetcore-angular/actions/workflows/azure-webapps-dotnet-core.yml/badge.svg?branch=deploy)](https://github.com/damienbod/bff-aspnetcore-angular/actions/workflows/azure-webapps-dotnet-core.yml) [![License](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg)](https://github.com/damienbod/bff-aspnetcore-angular/blob/main/LICENSE)\n\n## Setup Server\n\nThe 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.\n\n\u003e [!IMPORTANT]  \n\u003e In production, the Angular nx project is built into the **wwwroot** of the .NET project.\n\n![BFF production](https://github.com/damienbod/bff-aspnetcore-angular/blob/main/images/bff-arch-production_01.png)\n\nConfigure 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.\n\n\u003e [!IMPORTANT]  \n\u003e In a real Angular project, the additional dev routes need to be added so that the __dev refresh__ works!\n\n```json\n \"UiDevServerUrl\": \"https://localhost:4201\",\n \"ReverseProxy\": {\n    \"Routes\": {\n      \"assets\": {\n        \"ClusterId\": \"cluster1\",\n        \"Match\": {\n          \"Path\": \"assets/{**catch-all}\"\n        }\n      },\n      \"routealljs\": {\n        \"ClusterId\": \"cluster1\",\n        \"Match\": {\n          \"Path\": \"{nomatterwhat}.js\"\n        }\n      },\n      \"routeallcss\": {\n        \"ClusterId\": \"cluster1\",\n        \"Match\": {\n          \"Path\": \"{nomatterwhat}.css\"\n        }\n      },\n      \"webpacklazyloadingsources\": {\n        \"ClusterId\": \"cluster1\",\n        \"Match\": {\n          \"Path\": \"/src_{nomatterwhat}_ts.js\"\n        }\n      },\n      \"signalr\": {\n        \"ClusterId\": \"cluster1\",\n        \"Match\": {\n          \"Path\": \"/ng-cli-ws\"\n        }\n      },\n      \"webpacknodesrcmap\": {\n        \"ClusterId\": \"cluster1\",\n        \"Match\": {\n          \"Path\": \"/{nomatterwhat}.js.map\"\n        }\n      }\n    },\n    \"Clusters\": {\n      \"cluster1\": {\n        \"HttpClient\": {\n          \"SslProtocols\": [\n            \"Tls12\"\n          ]\n        },\n        \"Destinations\": {\n          \"cluster1/destination1\": {\n            \"Address\": \"https://localhost:4201/\"\n          }\n        }\n      }\n    }\n  }\n```\n\n## Setup Angular nx\n\nAdd the certificates to the nx project for example in the **/certs** folder\n\nUpdate the nx project.json file:\n\n```json\n\"serve\": {\n    \"executor\": \"@angular-devkit/build-angular:dev-server\",\n    \"options\": {\n    \"browserTarget\": \"ui:build\",\n    \"sslKey\": \"certs/dev_localhost.key\",\n    \"sslCert\": \"certs/dev_localhost.pem\",\n    \"port\": 4201\n},\n```\n\n\u003e [!NOTE]  \n\u003e The default Angular setup uses port 4200, this needs to match the YARP reverse proxy settings for development.\n\nUpdate the outputPath for the (nx build) to deploy the production paths to the wwwroot of the .NET project\n\n```\n \"build\": {\n      \"executor\": \"@angular-devkit/build-angular:browser\",\n      \"outputs\": [\"{options.outputPath}\"],\n      \"options\": {\n        \"outputPath\": \"../server/wwwroot\",\n        \"index\": \"./src/index.html\",\n        \"main\": \"./src/main.ts\",\n        \"polyfills\": [\"zone.js\"],\n        \"tsConfig\": \"./tsconfig.app.json\",\n        \"assets\": [\"./src/favicon.ico\", \"./src/assets\"],\n        \"styles\": [\"./src/styles.scss\"],\n        \"scripts\": []\n      },\n```\n\n\u003e [!NOTE]  \n\u003e When creating a new Angular nx project, it adds git files as well, delete these as this is not required.\n\n## Setup development\n\nThe 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.\n\n![BFF development](https://github.com/damienbod/bff-aspnetcore-angular/blob/main/images/bff-arch-development_01.png)\n\n\u003e [!NOTE]  \n\u003e Always run in HTTPS, both in development and production\n\n```\nnx server --ssl\n```\n\n## Azure App Registration setup\n\nThe application(s) are deployed as one. This is an OpenID Connect confidential client with a user secret or a certification for client assertion.\n\nUse the Web client type on setup.\n\n![BFF Azure registration](https://github.com/damienbod/bff-aspnetcore-angular/blob/main/images/azure-app-registration_01.png)\n\nThe 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.\n\n```csharp\nvar scopes = configuration.GetValue\u003cstring\u003e(\"DownstreamApi:Scopes\");\nstring[] initialScopes = scopes!.Split(' ');\n\nservices.AddMicrosoftIdentityWebAppAuthentication(configuration, \"MicrosoftEntraID\")\n    .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)\n    .AddMicrosoftGraph(\"https://graph.microsoft.com/v1.0\", initialScopes)\n    .AddInMemoryTokenCaches();\n\nservices.AddControllersWithViews(options =\u003e\n    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()));\n\nservices.AddRazorPages().AddMvcOptions(options =\u003e\n{\n    //var policy = new AuthorizationPolicyBuilder()\n    //    .RequireAuthenticatedUser()\n    //    .Build();\n    //options.Filters.Add(new AuthorizeFilter(policy));\n}).AddMicrosoftIdentityUI();\n```\n\nAdd the Azure App registration settings to the **appsettings.Development.json** and the **ClientSecret** to the user secrets.\n\n```json\n\"MicrosoftEntraID\": {\n    \"Instance\": \"https://login.microsoftonline.com/\",\n    \"Domain\": \"[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com]\",\n    \"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]\",\n    \"ClientId\": \"[Enter the Client Id (Application ID obtained from the Azure portal), e.g. ba74781c2-53c2-442a-97c2-3d60re42f403]\",\n    \"ClientSecret\": \"[Copy the client secret added to the app from the Azure portal]\",\n    \"ClientCertificates\": [\n    ],\n    // the following is required to handle Continuous Access Evaluation challenges\n    \"ClientCapabilities\": [ \"cp1\" ],\n    \"CallbackPath\": \"/signin-oidc\"\n},\n```\n\nApp Service (linux plan) configuration \n\n```\nMicrosoftEntraID__Instance               --your-value--\nMicrosoftEntraID__Domain                 --your-value--\nMicrosoftEntraID__TenantId               --your-value--\nMicrosoftEntraID__ClientId               --your-value--\nMicrosoftEntraID__CallbackPath           /signin-oidc\nMicrosoftEntraID__SignedOutCallbackPath  /signout-callback-oidc\n```\n\nThe client secret or client certificate needs to be setup, see Microsoft Entra ID documentation.\n\n## Debugging\n\nStart the Angular project from the **ui** folder\n\n```\nnx serve --ssl\n```\n\nStart the ASP.NET Core project from the **server** folder\n\n```\ndotnet run\n```\n\nOr just open Visual Studio and run the solution.\n\n## github actions build\n\nGithub 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.\n\n```yaml\n\nname: .NET and npm build\n\non:\n  push:\n    branches: [ \"main\" ]\n  pull_request:\n    branches: [ \"main\" ]\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n\n    steps:\n\n      - uses: actions/checkout@v3\n      - name: Setup .NET\n        uses: actions/setup-dotnet@v3\n        with:\n          dotnet-version: 8.0.x\n\n      - name: Restore dependencies\n        run: dotnet restore\n\n      - name: npm setup\n        working-directory: ui\n        run: npm install\n\n      - name: ui-nx-build\n        working-directory: ui\n        run: npm run build\n\n      - name: Build\n        run: dotnet build --no-restore\n      - name: Test\n        run: dotnet test --no-build --verbosity normal\n```\n\n## github actions Azure deployment\n\nThe deployment pipeline builds both projects and deploys this to Azure using an Azure App Service. See **azure-webapps-dotnet-core.yml**\n\ndeployment test server: https://bff-angular-aspnetcore.azurewebsites.net\n\n## Credits and used libraries\n\n- NetEscapades.AspNetCore.SecurityHeaders\n- Yarp.ReverseProxy\n- Microsoft.Identity.Web\n- ASP.NET Core\n- Angular \n- Nx\n\n## Angular nx Updates\n\n```\nnx migrate latest\n\nnx migrate --run-migrations=migrations.json\n```\n\n## Links\n\nhttps://learn.microsoft.com/en-us/aspnet/core/introduction-to-aspnet-core\n\nhttps://nx.dev/getting-started/intro\n\nhttps://github.com/AzureAD/microsoft-identity-web\n\nhttps://github.com/isolutionsag/aspnet-react-bff-proxy-example\n\nhttps://github.com/damienbod/bff-auth0-aspnetcore-angular\n\nhttps://github.com/damienbod/bff-openiddict-aspnetcore-angular\n\nhttps://github.com/damienbod/bff-azureadb2c-aspnetcore-angular\n\nhttps://github.com/damienbod/bff-aspnetcore-vuejs\n\nhttps://github.com/damienbod/bff-MicrosoftEntraExternalID-aspnetcore-angular\n","funding_links":[],"categories":["C#","C\\#"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdamienbod%2Fbff-aspnetcore-angular","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdamienbod%2Fbff-aspnetcore-angular","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdamienbod%2Fbff-aspnetcore-angular/lists"}