Home NewsX AD B2C authentication for Static Web App & API scenario

AD B2C authentication for Static Web App & API scenario

by info.odysseyx@gmail.com
0 comment 11 views


Application overview

The purpose of this sample application is to use Azure Active Directory B2C (Azure AD B2C) for authentication and authorization in a full-stack web application using a React frontend (deployed as an Azure Static Web App), a backend API written in: It shows you how. An Express (Deploy with Azure App Service) CI/CD pipeline that connects to a SQL database is set up using GitHub Actions to automate the build and deployment process.

application architecture

The source code for this application can be found at: naveedkharadi/swa-nodejs-sql (github.com)

The application architecture diagram is as follows:

su-API-sql.png

This diagram shows the components involved in the application.

  1. Azure static web app: Hosts a React front-end application and provides a URL to access the application.
  2. Azure web app: Hosts the Express backend API and provides a URL to access the API.
  3. Azure SQL Database: Stores data about applications accessed by backend APIs.
  4. Azure AD B2C: Handles authentication and authorization for the application, allowing users to log in and access the application.
  5. GitHub Operations: Provides a CI/CD pipeline to automate the build and deployment process.

The app architecture involved in app registration is depicted in the following diagram: (source: microsoft document)

spa-app-with-api-architecture.png

prerequisites

  1. Azure subscription:

    • An active Azure subscription is required to deploy applications to Azure services such as Azure Static Web Apps and Azure Web Apps.
  2. Azure AD B2C tenant:

    • You need an Azure AD B2C tenant to handle authentication and authorization.
    • App registrations for frontend and backend must be created in the Azure AD B2C tenant.
    • Policies for sign-in and registration must be configured in your Azure AD B2C tenant. For this application, a user flow named B2C_1_Sign_Up_Sign_In It has been used.
  3. Node.js and npm:

    • Node.js and npm (Node Package Manager) must be installed on your local development system.
    • This is required to run and build the React frontend and Express backend.
  4. Azure CLI (optional):

    • Azure CLI must be installed and configured on your local machine.
    • It is used to deploy applications to Azure and manage Azure resources.
  5. GitHub account:

    • To use GitHub Actions for CI/CD, you need a GitHub account.
    • To take advantage of the GitHub Actions workflow, your repository must be hosted on GitHub.
  6. visual studio code:

    • We recommend using Visual Studio Code (VS Code) to edit and manage project files.
    • Extensions for Azure and GitHub integration may help.
  7. GitHub account:

  8. visual studio code:

    • Install Visual Studio Code.
    • Recommended extensions:
      • Azure account
      • Azure App Service
      • Azure static web app
  9. Azure SQL Database:

    • You need Azure SQL Database to store data for your application. For this demo, you can use the free tier of Azure SQL Database.
    • The database schema and initial data can be set up using the SQL script available at: 1-database directory.

folder structure

main components

Backend (Express)

  • environment variables: For local development and testing, the backend uses environment variables defined in: .env For configuring database connectivity and authentication. In production, these environment variables are set in the Azure portal or using the Azure CLI.
  • database connection:The backend connects to a SQL database using: mssql package.
  • proof: The backend uses JWT for authentication with keys retrieved from Azure AD B2C.
  • API endpoint:
    • GET /employees: Get a list of employees from the database.
    • GET /employees/id: Get single employee by ID from database.
    • POST /employees: Add a new employee to the database.

Frontend (React)

  • environment variables: For local development and testing, the frontend uses environment variables defined in: .env For Microsoft Authentication Library (MSAL) configuration and API root URL. In production, these environment variables are set in the GitHub Actions workflow.
  • MSAL Configuration: The frontend is configured to use MSAL for Azure AD B2C authentication.
  • build process: React applications are built using: npm run buildOutput the built file as follows: build/ directory.

CI/CD workflow

Azure static web app (frontend)

Azure web app (backend)

authentication mechanism

React Frontend

The React frontend uses Microsoft Authentication Library (MSAL) for Azure AD B2C authentication. The main components involved are:

  1. MSAL configuration:

    • The configuration for MSAL is defined here: src/config.js:
    export const msalConfig = {  
        auth: {  
            clientId: process.env.REACT_APP_CLIENT_ID, 
            authority: process.env.REACT_APP_AUTHORITY, 
            redirectUri: process.env.REACT_APP_REDIRECT_URI, 
            knownAuthorities: [process.env.REACT_APP_KNOWN_AUTHORITIES], 
            postLogoutRedirectUri: process.env.REACT_APP_POST_LOGOUT_REDIRECT_URI, 
        },  
    };  
    
    export const appConfig = {  
        apiRootUrl: process.env.REACT_APP_API_ROOT_URL, 
        loginRequest: {  
            scopes: process.env.REACT_APP_SCOPES.split(' '), 
        },  
    };
    
    • This configuration uses environment variables to set the client ID, permissions, redirect URI, known permissions, and redirect URI after logout.
  2. Environment variables:

    • For local development and testing, environment variables are .env file:
    REACT_APP_CLIENT_ID=
    REACT_APP_AUTHORITY=https://.b2clogin.com/.onmicrosoft.com/
    REACT_APP_REDIRECT_URI=
    REACT_APP_KNOWN_AUTHORITIES=.b2clogin.com
    REACT_APP_POST_LOGOUT_REDIRECT_URI=
    REACT_APP_API_ROOT_URL=
    REACT_APP_SCOPES=
    

    memo: When deploying your application, React apps do not have access to NodeJS type environments, so you need to provide these environment variables to your build pipeline using GitHub variables, as seen in the workflow file (azure-static-web-apps-delightful-pebble-0bec84b00.yml).

  3. Usage in components:

    • MSAL configuration is used by React components to handle authentication flows such as login, logout, and token acquisition.

express backend

The Express backend uses: JWT (JSON Web Token) For authentication, the key is obtained from: Azure AD B2C. The main components involved are:

  1. JWT middleware:

    • The backend is express-jwt and jwks-rsa A package that validates JWT tokens. AD B2C uses key rotation, so keys are pulled dynamically from the JWKS endpoint.
    • The middleware consists of: api.js:
      const authenticateToken = jwt({
      secret: jwksRsa.expressJwtSecret({
          cache: true,
          rateLimit: true,
          jwksUri: `https://${config.b2cTenant}.b2clogin.com/${config.b2cTenant}.onmicrosoft.com/${config.b2cPolicy}/discovery/v2.0/keys`
      }),
      audience: `${config.audience}`,
      issuer: `https://${config.b2cTenant}.b2clogin.com/${config.tenantId}/v2.0/`,
      algorithms: ['RS256']
      });     
      
    • audience The client ID of your API application (can be obtained from app registration).
    • issuer Issuer URL for the B2C tenant.
    • jwkUri URL of the JWKS endpoint to retrieve the key. This can be obtained from the B2C metadata endpoint, available at: https://.b2clogin.com/.onmicrosoft.com//v2.0/.well-known/openid-configuration.
  2. environment variables:

    memo: If you deploy your application to Azure App Service, you must set these environment variables in the Azure portal or using the Azure CLI.

  3. protected path:

    • that authenticateToken Middleware is used to secure routes so that only authenticated users can access them.

Application launch settings

  1. Install dependencies:

    • Go to the frontend directory (3-swa) and run it. npm install.
    • Go to the backend directory (2-api) and run it. npm install.
  2. environment variables:

    • making .env Save files in both frontend and backend directories.
    • Add the required environment variables as specified next. README.md.
  3. Build and run your application locally:

    • Build a React frontend using: npm run build at 3-swa directory.
    • Run the Express backend using: npm start at 2-api directory.
  4. Deploy to Azure:

  5. CI/CD settings:

    • Configure a GitHub Actions workflow for CI/CD.
    • Create secrets and variables in your GitHub repository settings.
    • Update the workflow file with the required environment variables.
  6. Application testing:

    • Test your application by accessing the deployed frontend URL.
    • Verify that authentication and data retrieval functions work as expected.

NaveedKharadiMSFT_3-1729261153429.png

Additional Resources





Source link

You may also like

Leave a Comment

Our Company

Welcome to OdysseyX, your one-stop destination for the latest news and opportunities across various domains.

Newsletter

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

Laest News

@2024 – All Right Reserved. Designed and Developed by OdysseyX