Table of Contents

    Book an Appointment

    How Did We Uncover This Authentication Challenge?

    While working on a SaaS platform for the financial services sector, we needed to deploy a highly scalable, lightweight web portal. The architecture was straightforward: a statically hosted Single Page Application (SPA) communicating with a serverless backend powered by Azure Functions. To meet strict compliance requirements, the entire system had to be secured using Microsoft Entra ID (formerly Azure Active Directory).

    We integrated a Microsoft authentication library to allow users to log into the SPA. The sign-in process worked perfectly. However, when the frontend attempted to call the secured Azure Function using a standard fetch() request with an Authorization: Bearer {token} header, the API consistently returned a 403 Forbidden response.

    Despite the user being successfully authenticated on the client side, the serverless backend refused to accept the token. This authentication boundary breakdown is a frequent stumbling block in distributed architectures. We realized that passing a token is not enough; the token must be explicitly minted for the correct audience. We are sharing this engineering insight to help teams avoid this common token misconfiguration when they secure serverless APIs.

    Why Do Cross-Origin Serverless APIs Reject Valid Users?

    In our architecture, the Azure Function App was protected using built-in App Service Authentication (often referred to as “Easy Auth”) configured with Microsoft as the Identity Provider. The SPA, hosted statically on a separate domain, successfully acquired a token after the user authenticated.

    When the SPA executed the fetch() call to the backend endpoint, it attached the acquired token. Because the frontend and backend lived on different domains, this was a Cross-Origin Resource Sharing (CORS) request. While CORS misconfigurations often manifest as network errors, a 403 Forbidden status specifically indicated that the request reached the Azure Function’s authentication module, but the token itself was deemed invalid or unauthorized for that specific resource.

    When companies hire software developer teams to build distributed systems, ensuring that authentication contexts map perfectly between the frontend client and the backend API is critical. A token valid for signing a user into a web page is not inherently valid for executing backend functions.

    Analyzing the 403 Forbidden and Token Audience Mismatch

    To diagnose the failure, we intercepted the bearer token being sent by the SPA and decoded it using a JWT parsing tool. The issue became immediately apparent by looking at the aud (audience) and scp (scope) claims.

    The SPA was requesting and receiving an ID Token, which is designed strictly to prove that the user authenticated successfully to the client application. The Azure Function, however, requires an Access Token specifically scoped to its own App Registration identity.

    Here is what went wrong at an architectural level:

    • Audience Mismatch: The token acquired by the frontend had an audience intended for the Microsoft Graph API or the SPA itself, not the backend Azure Function.
    • Missing API Scopes: The Entra ID App Registration was not configured to expose an API, meaning the frontend could not request a permission scope like api://{backend-client-id}/RunFunction.
    • CORS Blocking Preflight: The Azure Function was not configured to accept the Authorization header in the preflight OPTIONS request from the SPA domain.

    How Did We Evaluate Entra ID Integration Strategies?

    To resolve this, we mapped out how the frontend and backend should communicate within the Microsoft Entra ID ecosystem. We considered three distinct architectural approaches.

    Could We Rely Solely on Passing the ID Token?

    We initially considered configuring the Azure Function to accept the frontend’s ID token. While this is technically possible by tweaking the allowed token audiences in the Easy Auth configuration, it violates the OAuth 2.0 specification. ID tokens are meant for client-side consumption, not for securing backend APIs. Relying on them introduces security risks, especially in enterprise environments.

    Should We Use a Single App Registration with Exposed APIs?

    Another approach was to use a single Microsoft Entra App Registration for both the SPA and the Azure Function. We could expose an API scope within this single registration and have the SPA request an access token for it. While easier to manage, this couples the frontend and backend identities. If you plan to hire azure developers for serverless architecture, they will often advise against this because it limits granular role-based access control (RBAC) if the backend scales to serve multiple different clients.

    Why Did We Choose Decoupled App Registrations?

    For enterprise-grade security, we opted for two separate Entra ID App Registrations: one for the SPA and one for the Azure Function. We exposed an API on the backend App Registration and granted the SPA App Registration permission to consume it. This decoupled approach provides distinct audit trails, allows independent scaling and is the gold standard when you hire dotnet developers for enterprise modernization who are accustomed to strict microservice security boundaries.

    Configuring MSAL and Azure Function Authentication

    To implement the decoupled architecture, we executed a precise configuration sequence across Microsoft Entra ID, the Azure Function and the frontend codebase.

    Backend Entra ID Configuration

    First, we configured the backend App Registration to expose an API:

    • Navigated to the backend App Registration in Entra ID.
    • Under Expose an API, we set the Application ID URI (e.g., api://{backend-client-id}).
    • We added a scope named access_as_user (resulting in api://{backend-client-id}/access_as_user).

    Frontend Entra ID Configuration

    Next, we gave the SPA permission to call the backend:

    • In the frontend App Registration, we went to API permissions.
    • Selected Add a permission -> My APIs and selected the backend App Registration.
    • Checked the access_as_user scope and granted admin consent.

    Implementing the Token Acquisition in the SPA

    We updated the frontend JavaScript to use standard MSAL.js practices to silently acquire an Access Token specifically for the backend scope. The previous implementation was attempting to use raw authentication wrappers without scope precision.

    const msalConfig = {
        auth: {
            clientId: "{frontend-client-id}",
            authority: "https://login.microsoftonline.com/{tenant-id}",
            redirectUri: window.location.origin
        }
    };
    const msalInstance = new msal.PublicClientApplication(msalConfig);
    async function callSecureFunction() {
        const account = msalInstance.getAllAccounts()[0];
        
        if (!account) {
            console.error("User is not signed in.");
            return;
        }
        const tokenRequest = {
            scopes: ["api://{backend-client-id}/access_as_user"],
            account: account
        };
        let response;
        try {
            // Attempt to acquire token silently
            response = await msalInstance.acquireTokenSilent(tokenRequest);
        } catch (error) {
            if (error instanceof msal.InteractionRequiredAuthError) {
                // Fallback to popup if silent acquisition fails
                response = await msalInstance.acquireTokenPopup(tokenRequest);
            } else {
                throw error;
            }
        }
        // Call the Azure Function with the correct Access Token
        const result = await fetch("https://api.generic-tenant.azurewebsites.net/api/ExecuteTask", {
            method: "GET",
            headers: { 
                "Authorization": `Bearer ${response.accessToken}`,
                "Content-Type": "application/json"
            }
        });
        if (result.ok) {
            console.log("Secure call successful:", await result.text());
        } else {
            console.error("Secure call failed with status:", result.status);
        }
    }
    

    Configuring Azure Function CORS

    Finally, we navigated to the Azure Function App configuration in the portal. Under the CORS settings, we added the explicit domain of the GitHub Pages repository (e.g., https://spa.genericdomain.com) and checked the box to enable Access-Control-Allow-Credentials. This allowed the preflight OPTIONS request to succeed and pass the Authorization header through to the Easy Auth module.

    What Are the Best Practices for Secure Serverless Architectures?

    This implementation highlighted several architectural principles that engineering teams should adopt when bridging static frontends and secure backends:

    • Never use ID tokens for API authorization: Always request an Access Token using explicit custom scopes exposed by the destination API.
    • Decouple App Registrations: Maintain separate Entra ID configurations for clients and APIs. This ensures granular security control and better auditability.
    • Inspect your JWTs: When facing 401 or 403 errors, decode the token. Ensure the aud (audience) matches the backend’s App ID URI and the scp (scope) contains the required permissions.
    • Configure strict CORS boundaries: Never use wildcard (*) CORS policies on authenticated endpoints. Always specify the exact client domain.
    • Handle silent token acquisition fallbacks: Access tokens expire quickly. It’s vital to hire frontend developers for secure spa projects who know how to implement acquireTokenSilent with proper interactive fallbacks (popups or redirects) to maintain a seamless user experience.

    Bringing Secure Authentication Together

    Authentication boundaries between static applications and serverless APIs can be notoriously difficult to configure. A 403 Forbidden error in this context usually points directly to a token audience mismatch or a missing API scope. By explicitly exposing an API on the backend, granting permission to the frontend and requesting an access token for that specific scope, we successfully secured the Azure Function while maintaining a seamless user login experience.

    If your team is navigating complex Microsoft Entra ID integrations or modernizing cloud architectures, contact us to explore how our dedicated remote engineering teams can accelerate your secure software delivery.

    Social Hashtags

    #AzureFunctions #MicrosoftEntraID #AzureSecurity #AzureAuthentication #ServerlessComputing #CloudSecurity #MSAL #OAuth2 #APISecurity #MicrosoftAzure #SinglePageApplication #CloudArchitecture #IdentityManagement #AzureDevelopment #SecureByDesign

    Frequently Asked Questions