Microsoft Entra integration

This guide covers how to use Microsoft Entra to authenticate with a Fauna database.

When set up, Entra issues a JWT when end users log into your application. The JWT contains a Fauna token's authentication secret for the user in a private claim. Your application can use the secret to run queries on the user’s behalf.

Before you start

To complete this guide, you’ll need:

  • A Microsoft Azure account.

  • Familiarity with Microsoft Entra and Azure Functions.

Authentication flow

In this guide, you’ll set up an Azure function that creates a Fauna token when Entra issues a JWT. You’ll configure Entra to use a custom claim provider to add the token’s secret as a claim to the JWT.

The setup uses the following authentication flow:

  1. The client sends a request to Microsoft Entra. Entra invokes an Azure Function in the token (JWT) issuance phase.

  2. The Azure Function generates a Fauna token and includes the token’s secret in a private fauna_token_secret claim in the payload of the JWT issued by Entra.

  3. Entra returns the JWT to the client application. The client application uses the token secret to authenticate Fauna queries on the user’s behalf.

For more on the general flow and setup, see Create a REST API for a token issuance start event in Azure Functions in the Microsoft Entra docs.

Configure Fauna

  1. Log in to the Fauna Dashboard and select your database.

  2. In the Dashboard Shell, run the following FQL query to create a key with the server role:

    Key.create({
      role: "server"
    })
    {
      id: "404130885316640841",
      coll: Key,
      ts: Time("2099-07-22T17:08:15.803Z"),
      role: "server",
      secret: "fn..."
    }

    Copy the key’s secret. You’ll use it later.

  3. Create a collection to store identity documents for your application’s end users.

    Edit the collection’s schema to include an email field or similar identifier used to uniquely identify users. For example:

    collection Customer {
      unique [.email]
    
      index byEmail {
        terms [.email]
      }
    }
  4. Create one or more user-defined roles.

    Edit the role’s schema to include the previous collection in the role’s membership property. For example:

    role customer {
      membership Customer
    
      privileges Product {
        read
      }
      ...
    }

Create a REST API in Azure

Use an Azure Function to create a REST API. The API creates a Fauna token for an end user.

Create a Azure functions app

  1. Sign in to the Azure Portal.

  2. From the Home page, select Create a resource.

  3. Search for and select Function App. Then select Create > Function App.

  4. Create a function app with the following settings:

    Settings Value Description

    Plan

    Consumption (Serverless)

    Hosting plan that defines how resources are allocated to your function app.

    Subscription

    Your subscription

    The subscription under which the new function app will be created.

    Function App name

    Enter a unique name

    A unique name that identifies your new function app.

    Runtime

    Node.js

    This guide uses Node.js. You can use any runtime with a supported Fauna driver.

    Version

    20 LTS

    Region

    Your preferred region

    Operating System

    Windows

  5. Select Review + create and then select Create. It may take a few minutes for Azure to deploy the function app.

  6. Once deployed, select Go to resource.

Set up environment variables

  1. In the Azure Portal, navigate to your function app.

  2. In the function app’s Overview page, click Settings > Environment variables in the left navigation.

  3. Click Add.

  4. In the Add/Edit application setting pane, enter the following:

    • Name: FAUNA_SECRET

    • Value: The Fauna key’s secret you copied earlier.

  5. Click Apply.

  6. On the Environment variables page, click Apply. Then click Confirm.

Create an HTTP trigger function

Create an HTTP trigger function in the Azure function app. The HTTP trigger lets you invoke a function with an HTTP request and is referenced by your Microsoft Entra custom authentication extension.

  1. Navigate to the function app’s Overview page.

  2. . In the Functions tab, and select Create function under Create in Azure portal.

  3. Select the HTTP trigger template and select Next.

  4. Enter a Function name and leave the Authorization level as Function. Then click Create.

  5. Add the following code to the function:

    const { Client, fql, FaunaError } = require("fauna");
    
    module.exports = async function (context, req) {
        // Read the request body
        const requestBody = req.body;
    
        // Parse the request body
        const data = requestBody ? JSON.parse(requestBody) : null;
        const email = data?.data?.authenticationContext?.user.mail;
    
        const client = new Client({
          secret: process.env.FAUNA_SECRET,
        });
    
        const fauna_response = await client.query(fql`
          // If a Customer document with the email exists, get it.
          // Otherwise, create a Customer document.
          let user = Customer.byEmail(${email}).first() ??
            Customer.create({email: ${email}})
          // Create a token for the Customer document.
          let token = Token.create({
            document: user,
            ttl: Time.now().add(30, 'minutes')
          })
          // Return the Customer document's ID and the
          // token's secret.
          let payload = {
            userId: user!.id,
            token: token.secret
          }
          payload
        `);
    
        // Prepare the response object
        const response = {
            data: {
                '@odata.type': 'microsoft.graph.onTokenIssuanceStartResponseData',
                actions: [
                    {
                        '@odata.type': 'microsoft.graph.tokenIssuanceStart.provideClaimsForToken',
                        claims: {
                            FaunaTokenSecret: fauna_response.data.token,
                        }
                    }
                ]
            }
        };
    
        // Return the response
        context.res = {
            status: 200,
            body: response
        };
    };
  6. Save the function.

  7. Click Get function URL.

  8. Copy the default (Function key) URL.

Install the Fauna driver

  1. Navigate to the function app’s Overview page.

  2. In the left navigation, select Development Tools > Console.

  3. Navigate to the http trigger function’s directory. For example:

    cd HttpTrigger1
  4. In the directory, run the following commands to install the Fauna driver:

    npm init -y
    npm install fauna --save

Register a custom authentication extension

  1. In the top navigation, click Home.

  2. Search for and select Microsoft Entra ID.

  3. From the Entra Overview page, select Enterprise applications > Custom authentication extensions > Create a custom extension.

  4. In the Basics tab, select the TokenIssuanceStart event type and click Next.

  5. In the Endpoint Configuration tab, enter the following:

    • Name: Enter a name for the custom extension.

    • Target URL: The Azure function URL you copied earlier.

  6. Select Next.

  7. In API Authentication tab, you will be presented with an option to select a app registration type. Select Create new app registration.

  8. Enter an application Name and select Next.

  9. In the Claims tab, enter the following claim:

    • FaunaTokenSecret

  10. Select Next and then click Create.

It may take a few minutes for Azure to create the application and custom extension. Once created, you’ll navigate to the custom extension’s Overview page.

  1. On the custom extension’s Overview page, copy the App ID under API Authentication. You’ll use the ID later in the guide.

  2. Under API Authentication, click Grant permission.

  3. If prompted, sign in to Azure and accept the permissions request.

Configure an OpenID Connect app

To get a token and test the custom authentication extension, you can use the https://jwt.ms app from Microsoft.

Register a test web app

  1. In the top navigation, click Home.

  2. Search for and select Microsoft Entra ID.

  3. In left navigation, select App registrations > New registration.

  4. Enter a Name for the application. For example, My test application.

  5. Under Supported account types, select Accounts in this organizational directory only.

  6. Under Redirect URI, select Web and enter https://jwt.ms as the URL.

  7. Click Register.

    Register Test Web Application

  8. In the app registration’s Overview page, copy the:

    • Application (client) ID

    • Directory (tenant) ID

    Copy Application ID

Enable implicit flow

  1. From the app registration’s Overview page, navigate to Manage > Authentication.

  2. Under Implicit grant and hybrid flows, check ID tokens.

  3. Click Save.

Enable claims mapping policy

  1. In the left navigation, navigate to Manage > Manifest.

  2. In the manifest, locate the acceptMappedClaims attribute, and set the value to true.

  3. Set the accessTokenAcceptedVersion to 2.

  4. Select Save to save the changes.

The following JSON snippet demonstrates how to configure these properties.

{
  "acceptMappedClaims": true,
  "accessTokenAcceptedVersion": 2
  // .... rest of the manifest
}

Assign a custom claims provider to your app

  1. In the top navigation, click Home.

  2. Search for and select Microsoft Entra ID.

  3. In the left navigation, select Manage > Enterprise applications.

  4. Find and select the application you created from the list.

  5. From the Overview page, select Manage >Single sign-on in the left navigation.

  6. Next to Attributes & Claims, select Edit.

    Assign attributes

  7. Expand Advanced settings.

  8. Next to Custom claims provider, select Configure

  9. In the Customer claims provider pane, select the custom claims provider you created earlier.

  10. Click Save.

Next, assign the attributes from the custom claims provider, which should be issued into the token as claims:

  1. On the Attributes & Claims page, select Add new claim.

  2. Enter a Name of FaunaTokenSecret.

  3. Select a Source of Attribute.

  4. Select a Source attribute of "customClaimsProvider.FaunaTokenSecret".

  5. Select Save.

Protect your Azure Function

The custom authentication extension uses a server-to-server flow to obtain an access token. The token is sent in the HTTP Authorization header to your Azure function.

Use the following steps to add Microsoft Entra as an identity provider to your Azure Function app:

  1. In the top navigation, click Home. app you previously published.

  2. From the Home page, find and select the function app you created earlier.

  3. In the left navigation, select Settings > Authentication.

  4. Select Add identity provider.

  5. Select an Identity provider of Microsoft.

  6. Select a tenant type of Workforce configuration.

  7. Under App registration, select an App registration type of Pick an existing app registration. Then select the custom authentication extension app you created earlier.

  8. Enter the following issuer URL, https://login.microsoftonline.com/<TENANT_ID>/v2.0, where <TENANT_ID> is the Entra application’s tenant ID you copied earlier.

  9. Select a Unauthenticated requests of HTTP 401 Unauthorized .

  10. Uncheck Token store.

  11. Select Add.

    Add Identity Provider

Test the application

  1. Open a new private browser and navigate and sign-in through the following URL.

    https://login.microsoftonline.com/<TENANT_ID>/oauth2/v2.0/authorize?client_id=<CLIENT_ID>&response_type=id_token&redirect_uri=https://jwt.ms&response_mode=form_post&scope=openid&state=12345&nonce=678910
  2. Replace:

    • <TENANT_ID> with the Entra application tenant ID you copied earlier.

    • <CLIENT_ID> with the Entra application’s client ID you copied earlier.

  3. After logging in, you’ll be presented with your decoded token at https://jwt.ms. The decoded token will contain the FaunaTokenSecret claim field.

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!