Testing Dataverse with playwright-bdd, Part 1: Setup and Sign-In
By Betim Beja ·
End-to-end tests for a Dataverse model-driven app are hard to get right. You need a test that a functional consultant can read and confirm. You also need a tool that copes with the forms, the command bar and the asynchronous loading of a model-driven app. And before any of that, you need to sign in.
playwright-bdd covers the first two. You write the scenarios in Gherkin (Given / When / Then), which the business can read. playwright-bdd turns them into Playwright tests, so you keep the Playwright runner, its parallel workers, its traces and its locators.
This is a series in two parts:
Part 1 (this post): the project setup, and the part that usually stops these projects early: signing in to Dataverse as different users: with a password only, with an authenticator code, or with a passkey.
Part 2 (coming soon): using AI to write the Gherkin and the step definitions, then running everything in Azure Pipelines and reviewing the results with the Playwright BDD Report extension.
What you need
A Dataverse test environment. The scenarios create and delete data, so don't point them at production.
Dedicated test users, one per role you want to test (for example a salesperson and a sales manager). Each one needs a license and the security roles of that role. Using real people's accounts in automated tests causes trouble sooner or later.
Node.js 22.18 or later, which runs TypeScript files directly (we use that for a small helper script).
Project setup
Create a folder for the tests and install Playwright, playwright-bdd and a few helpers:
Every Dataverse page sends an anonymous visitor to login.microsoftonline.com. Signing in at the start of every scenario is slow, and it also looks like an attack to Microsoft Entra ID: dozens of sign-ins for the same account within minutes are the kind of thing that triggers throttling and risk policies.
Playwright's answer is storage state. A setup project signs in once, saves the cookies and local storage to a JSON file, and every test starts from that file already signed in. playwright-bdd supports this out of the box (see its authentication guide).
The interesting part is how each user signs in. In a real tenant you will meet some mix of these three kinds of user:
No MFA. Username and password only. This only happens when Conditional Access leaves the account out of the MFA policies, usually for test accounts in a test tenant. It is the simplest case, and it is getting rarer, as it should.
MFA with an authenticator app code (TOTP). The user enters a 6-digit code from an authenticator app. That code is computed from a secret key and the current time, so a test can compute it too. It works in any tenant that enforces MFA, but whoever has the password and the secret can sign in as the user.
Passkey. Since version 1.61, Playwright can play the authenticator itself: context.credentials is a virtual WebAuthn authenticator. You register a passkey for the test user once, keep its private key as a secret, and the test signs in with it. There is no password to leak or expire, no code to time, and a passkey counts as phishing-resistant MFA, so it also passes the Conditional Access policies that ask for the strongest kind of sign-in. This is the setup I recommend for test users, together with Conditional Access policies that let the passkey open Dataverse and nothing else (more on that below).
MFA that needs a person. Push notifications with number matching, Windows Hello, a passkey on a phone or a security key, SMS. These are built so that a script can't pass them. You can still use such an account locally: sign in yourself once, and let the tests reuse the session.
The setup below handles all four, and each user can be configured differently.
Describing the users
The scenarios refer to personas (salesperson, sales-manager, admin), never to accounts. The accounts come from environment variables, and which variables are set decides how the persona signs in:
users.ts
export const personas = ['salesperson', 'sales-manager', 'sales-vp', 'admin'] as const;export type Persona = (typeof personas)[number];/** Scenarios without an @as: tag run as this persona. */export const defaultPersona: Persona = 'salesperson';/** A passkey registered with Playwright's virtual authenticator, as printed by scripts/register-passkey.mts */export interface Passkey { id: string; rpId: string; userHandle: string; privateKey: string; publicKey: string; signCount?: number;}export interface TestUser { username: string; /** Not set for passkey users, nor for users who sign in interactively (push notification, ...). */ password?: string; /** Base32 secret of the user's authenticator app registration, when MFA asks for a code. */ totpSecret?: string; passkey?: Passkey;}/** Where the signed-in session of a persona is saved. Never commit this folder. */export const authFile = (persona: Persona) => `playwright/.auth/${persona}.json`;export function isPersona(value: string): value is Persona { return (personas as readonly string[]).includes(value);}/** * "sales-manager" reads DV_SALES_MANAGER_USERNAME, DV_SALES_MANAGER_PASSWORD, DV_SALES_MANAGER_TOTP_SECRET * and DV_SALES_MANAGER_PASSKEY. Returns undefined when the persona is not configured here. */export function getUser(persona: Persona): TestUser | undefined { const prefix = `DV_${persona.toUpperCase().replaceAll('-', '_')}`; const username = process.env[`${prefix}_USERNAME`]; if (!username) return undefined; const passkey = process.env[`${prefix}_PASSKEY`]; return { username, password: process.env[`${prefix}_PASSWORD`] || undefined, totpSecret: process.env[`${prefix}_TOTP_SECRET`] || undefined, passkey: passkey ? JSON.parse(passkey) : undefined, };}
Locally the variables come from a .env file. Here is an example with one persona of each kind:
.env.example
DATAVERSE_URL=https://contoso-test.crm4.dynamics.com# No MFA: excluded from the MFA policy by Conditional AccessDV_SALESPERSON_USERNAME=e2e.salesperson@contoso.onmicrosoft.comDV_SALESPERSON_PASSWORD=# MFA with an authenticator app code (TOTP)DV_SALES_MANAGER_USERNAME=e2e.salesmanager@contoso.onmicrosoft.comDV_SALES_MANAGER_PASSWORD=DV_SALES_MANAGER_TOTP_SECRET=# Passkey, from npm run register-passkey -- sales-vpDV_SALES_VP_USERNAME=e2e.salesvp@contoso.onmicrosoft.comDV_SALES_VP_PASSKEY=# Interactive (push notification, ...): no password here, you sign in yourselfDV_ADMIN_USERNAME=you@contoso.com
salesperson has a password and no TOTP secret, so it signs in with the password only.
sales-manager has both, so it signs in with the password and then enters a generated code.
sales-vp has a passkey and no password, so it signs in with the passkey alone.
admin has no password at all: that is your own account, and you sign in yourself.
A persona without a username is simply not configured in that environment. We will use this in the pipeline, where the interactive persona can't work.
Signing in
The sign-in function walks through the Microsoft Entra ID pages:
login.ts
import { expect, type Page } from '@playwright/test';import { TOTP } from 'otpauth';import type { Passkey, TestUser } from './users';/** Signs in to Microsoft Entra ID and waits until the browser is back on Dataverse. */export async function signIn(page: Page, dataverseUrl: string, user: TestUser) { if (user.passkey) { await signInWithPasskey(page, dataverseUrl, user.passkey); return; } // Dataverse sends an anonymous visitor to login.microsoftonline.com await page.goto(dataverseUrl); await page.locator('input[name="loginfmt"]').fill(user.username); await page.getByRole('button', { name: 'Next' }).click(); if (!user.password) { // Interactive: the person at the keyboard types the password and approves the MFA prompt await backOnDataverse(page, dataverseUrl, 5 * 60_000); return; } await page.locator('input[name="passwd"]').fill(user.password); await page.getByRole('button', { name: 'Sign in' }).click(); if (user.totpSecret) { await enterVerificationCode(page, user.totpSecret); } await backOnDataverse(page, dataverseUrl);}async function signInWithPasskey(page: Page, dataverseUrl: string, passkey: Passkey) { const context = page.context(); // Entra rejects a signature counter it has already seen, and a secret can't remember the last one. // The counter only has to grow, so the seconds since 1970 do the job. await context.credentials.create(passkey.rpId, { ...passkey, signCount: Math.floor(Date.now() / 1000) }); // From now on navigator.credentials in this context talks to the virtual authenticator await context.credentials.install(); // The sign-in page offers the passkey on its own and the virtual authenticator answers at once: // no username, no clicks await page.goto(dataverseUrl); await backOnDataverse(page, dataverseUrl);}async function enterVerificationCode(page: Page, secret: string) { const codeInput = page.locator('input[name="otc"]'); const signInAnotherWay = page.getByRole('link', { name: /sign in another way|can't use my microsoft authenticator app/i, }); // When the Authenticator app is the preferred method, Entra asks for a push approval first await expect(codeInput.or(signInAnotherWay).first()).toBeVisible(); if (!(await codeInput.isVisible())) { await signInAnotherWay.click(); await page.getByText(/use a verification code/i).click(); } const totp = new TOTP({ secret: secret.replace(/\s/g, '') }); // A code that expires while it is being submitted is rejected: wait for the next one const msLeft = totp.period * 1000 - (Date.now() % (totp.period * 1000)); if (msLeft < 5_000) await page.waitForTimeout(msLeft + 500); await codeInput.fill(totp.generate()); await page.getByRole('button', { name: 'Verify' }).click();}async function backOnDataverse(page: Page, dataverseUrl: string, timeout = 60_000) { const { origin } = new URL(dataverseUrl); const staySignedIn = page.getByRole('button', { name: 'Yes' }); await expect(async () => { // "Stay signed in?" shows up unless the tenant has turned it off if (await staySignedIn.isVisible()) await staySignedIn.click(); expect(new URL(page.url()).origin).toBe(origin); }).toPass({ timeout }); await page.waitForLoadState();}
A few details are worth explaining:
The verification code. If the user also has the Microsoft Authenticator app, system-preferred MFA sends a push notification first. In that case the function clicks "Sign in another way" and chooses the verification code. It also waits for a fresh code when the current one has less than 5 seconds left: a code that expires on its way to the server is rejected, and that makes a flaky test.
Passkeys.signInWithPasskey loads the passkey into the virtual authenticator before the first page opens. Entra's sign-in page offers passkeys on its own, right on the username page, and the virtual authenticator answers at once. The test doesn't even type the username.
The signature counter. Every time a passkey signs in, it reports a counter, and Entra rejects a value it has already seen with AADSTS135017: Unexpected Signature Counter. A passkey kept in a secret always starts from the same value, so only the first run would pass. The counter only has to grow, though, not grow by one: seeding it with the seconds since 1970 keeps it growing from run to run, with nothing to save in between.
"Stay signed in?". Whether this page appears depends on the tenant. Instead of guessing, backOnDataverse retries until the browser is back on the Dataverse URL, and clicks "Yes" if the question shows up along the way.
Interactive users. For them the function only fills in the username and then waits up to 5 minutes for you to finish: password, number matching, passkey, whatever your account uses.
Language. The locators use the English labels ("Next", "Sign in", "Verify"). That's why the config sets locale: 'en-US', which keeps the Microsoft sign-in pages in English. The language of the model-driven app itself comes from the user's personal settings in Dataverse, not from the browser.
Getting the TOTP secret
For a test user that signs in with a code, you need the secret key behind the code. You get it when you register an authenticator app for that user:
Choose Microsoft Authenticator. Don't worry about the name: the next page lets you use any authenticator app.
Choose Set up a different authentication app, then Next on the page that follows.
When the QR code appears, choose Can't scan the QR code?
Copy the Secret key with Copy key. This is the value for DV_SALES_MANAGER_TOTP_SECRET. It doesn't matter that it is in lowercase.
Choose Next. The wizard asks for a 6-digit code to confirm the registration.Generate the code from the secret key, and enter it within its 30 seconds:terminal
Treat this secret like a password, because together with the password it is the account. Keep it in your .env locally and in a secret variable (or Azure Key Vault) in the pipeline, and give the test user only the roles the scenarios need, in the test environment only.
Registering a passkey
First, the tenant has to accept the passkey Playwright creates. It comes without attestation and with an all-zero AAGUID (the identifier of the authenticator model), so in the Microsoft Entra admin center, under Authentication methods:
The Passkey (FIDO2) method is enabled for the test users, with Enforce attestation set to No and no key restrictions (or with 00000000-0000-0000-0000-000000000000 among the allowed AAGUIDs).
If a Conditional Access policy asks for an authentication strength that lists the allowed FIDO2 keys, the same AAGUID has to be allowed there.
Watch the Allow / Block choice next to the AAGUID list. When I set this up, I had chosen Block instead of Allow: the registration still went through, and only the sign-in failed.
When the passkey doesn't meet the policy, Entra says so after checking it: "Your sign-in was successful but this passkey does not meet the criteria set by your admin", and the sign-in logs show error 135016, "FIDO sign-in is disabled via policy". Policy changes can also take a few minutes to reach the sign-in.
The passkey must be created inside Playwright's authenticator, otherwise its private key ends up in a phone or a security key where no test can use it. This script opens a browser with the virtual authenticator, waits until Entra has created the passkey, and prints it:
register-passkey.mts
// Registers a passkey for a test user in Playwright's virtual authenticator and prints it for .env.// Usage: node scripts/register-passkey.mts sales-vpimport { setTimeout } from 'node:timers/promises';import { chromium } from '@playwright/test';const persona = process.argv[2] ?? 'sales-vp';const variable = `DV_${persona.toUpperCase().replaceAll('-', '_')}_PASSKEY`;const browser = await chromium.launch({ headless: false });const context = await browser.newContext({ locale: 'en-US' });// navigator.credentials now talks to the virtual authenticator instead of the real onesawait context.credentials.install();const page = await context.newPage();await page.goto('https://mysignins.microsoft.com/security-info');console.log(`Sign in as the ${persona} test user, then Add sign-in method > Passkey.`);// The authenticator is empty until Entra creates the passkey in itlet [passkey] = await context.credentials.get();for (const deadline = Date.now() + 10 * 60_000; !passkey && Date.now() < deadline; ) { await setTimeout(1_000); [passkey] = await context.credentials.get();}if (!passkey) throw new Error('No passkey was registered within 10 minutes');console.log(`\n${variable}='${JSON.stringify(passkey)}'\n`);console.log('Give the passkey a name in the browser, then close it.');await page.waitForEvent('close', { timeout: 0 });await browser.close();
terminal
node scripts/register-passkey.mts sales-vp
In the browser that opens, sign in as the test user with the methods it already has: its password and MFA, or a Temporary Access Pass for a new account. Real passkeys don't work in this browser, because the virtual authenticator replaces them.
On the Security info page, choose Add sign-in method and then Passkey, not "Passkey in Microsoft Authenticator".
Choose Next.
Entra moves to its own page to create the passkey. Choose Next once more. No security window opens: the virtual authenticator creates the passkey without asking.
Give the passkey a name that says where it lives, for example "Playwright e2e".
The passkey appears in the list as Passkey (Device bound). Close the browser.
The terminal shows the line for your .env: DV_SALES_VP_PASSKEY with the passkey as JSON, in single quotes. The same rules apply as for the TOTP secret: the private key in it is the account, so keep it in a secret variable, and delete the passkey from the Security info page when you no longer need it.
One side effect: as soon as an account has a passkey, Entra asks for the passkey before the password. Don't add a passkey to an account that one of your password personas signs in with: give the passkey persona its own test user.
Limiting what a leaked passkey can do
A passkey kept in a pipeline secret is still a credential that has left its authenticator: whoever reads the secret can sign in as the test user, from anywhere. Conditional Access makes that much less useful. Put the passkey test users in a group, and give that group two policies:
Passkey only. Target resource: Dataverse (the app with ID 00000007-0000-0000-c000-000000000000; some tenants still call it Common Data Service or Dynamics CRM). Grant: Require authentication strength, with a custom strength that allows only Passkeys (FIDO2) and, in its advanced options, only the all-zero AAGUID. A password, or a passkey anywhere else, doesn't get in.
Nothing but Dataverse. Target resources: All resources, excluding Dataverse. Grant: Block access.
With both in place, a leaked passkey opens Dataverse with the roles of that test user, in the test environments where that user exists, and nothing else: no mail, no Teams, no SharePoint, no Azure portal. Together with test-only roles in a test environment, there is very little left to attack. A few things to keep in mind:
Conditional Access needs a Microsoft Entra ID P1 license.
Register the passkey before you turn on the block, because the block can also cover the Security info page. To register a new one later, exclude the user from the block for the time it takes.
If a scenario uses another service from inside the app, for example SharePoint document management or a Power Automate flow, exclude that service from the block as well. Turn the policies on in report-only mode first, and check the sign-in logs while the scenarios run.
The setup project
The setup file signs in every configured persona and saves each session to playwright/.auth/<persona>.json:
auth.setup.ts
import { statSync } from 'node:fs';import { test as setup } from '@playwright/test';import { signIn } from './login';import { authFile, getUser, personas } from './users';/** A saved session younger than this is reused, so local runs don't sign in every time. */const SESSION_MAX_AGE = 8 * 60 * 60 * 1000;setup.describe.configure({ mode: 'parallel' });for (const persona of personas) { setup(`sign in as ${persona}`, async ({ page, baseURL, headless }) => { const file = authFile(persona); const user = getUser(persona); setup.skip(!user, `${persona} is not configured in this environment`); setup.skip(isFresh(file), `Reusing the session saved in ${file}`); if (!user!.password && !user!.passkey) { if (headless) { throw new Error(`${persona} signs in interactively. Run: npx playwright test --project=setup --headed`); } setup.setTimeout(6 * 60_000); } await signIn(page, baseURL!, user!); await page.context().storageState({ path: file }); });}function isFresh(file: string) { try { return Date.now() - statSync(file).mtimeMs < SESSION_MAX_AGE; } catch { return false; }}
Personas that are not configured are skipped, so the same code runs on your machine and in the pipeline.
A session saved less than 8 hours ago is reused. That keeps your local runs fast. It also means that you approve the MFA prompt of your own account once per day, not once per run.
An interactive persona can't sign in headless. Instead of hanging until the timeout, the setup fails with the command to run.
The Playwright config ties it together. The BDD project depends on the setup project:
playwright.config.ts
import 'dotenv/config';import { defineConfig, devices } from '@playwright/test';import { defineBddConfig } from 'playwright-bdd';const testDir = defineBddConfig({ features: 'features/**/*.feature', steps: 'steps/**/*.ts',});export default defineConfig({ // Model-driven apps take their time: give every scenario room to load forms timeout: 2 * 60_000, expect: { timeout: 15_000 }, use: { baseURL: process.env.DATAVERSE_URL, // Keeps the Microsoft sign-in pages in English, which the locators in auth/login.ts expect locale: 'en-US', trace: 'retain-on-failure', screenshot: 'only-on-failure', }, projects: [ // Signs in every persona once and saves the sessions to playwright/.auth { name: 'setup', testDir: 'auth', testMatch: /.*\.setup\.ts/ }, { name: 'dataverse', testDir, dependencies: ['setup'], use: { ...devices['Desktop Chrome'] }, }, ],});
Choosing the user for a scenario
The playwright-bdd authentication guide shows how to override the storageState fixture based on the scenario's tags, using the $tags fixture. We use that to pick the persona: a scenario tagged @as:sales-manager starts signed in as the sales manager. Without a tag, it runs as the default persona.
fixtures.ts
import { existsSync } from 'node:fs';import { test as base, createBdd } from 'playwright-bdd';import { authFile, defaultPersona, isPersona, type Persona } from '../auth/users';export const test = base.extend<{ persona: Persona }>({ // "@as:sales-manager" on a scenario, or on its feature, picks the user it runs as persona: async ({ $tags }, use) => { const tag = $tags.findLast((t) => t.startsWith('@as:')); const persona = tag ? tag.slice('@as:'.length) : defaultPersona; if (!isPersona(persona)) throw new Error(`Unknown persona in ${tag}`); await use(persona); }, storageState: async ({ persona }, use, testInfo) => { const file = authFile(persona); testInfo.skip(!existsSync(file), `No session for ${persona}: the user is not configured here`); await use(file); },});export const { Given, When, Then } = createBdd(test);
The tag can go on a scenario or on the whole feature. When both have one, the scenario wins, because $tags lists the feature tags first. If the persona has no saved session (it is not configured in this environment), the scenario is reported as skipped with the reason, instead of failing at the sign-in page.
A first feature checks that each persona lands in the app with the expected security role:
sign-in.feature
Feature: Signing in Scenario: A salesperson opens Sales Hub Given I open the "Sales Hub" app Then I have the "Salesperson" security role @as:sales-manager Scenario: A sales manager opens Sales Hub Given I open the "Sales Hub" app Then I have the "Sales Manager" security role @as:sales-vp Scenario: A sales VP opens Sales Hub Given I open the "Sales Hub" app Then I have the "Vice President of Sales" security role @as:admin Scenario: An administrator opens Sales Hub Given I open the "Sales Hub" app Then I have the "System Administrator" security role
The steps ask the client API (Xrm) instead of reading the page. Opening the app waits until getCurrentAppProperties() reports the app's unique name: Dataverse's error page ("Record Is Unavailable", when the app doesn't exist or the user can't open it) also has an Xrm object, so waiting for Xrm alone lets a scenario carry on from an error page. The security roles come from the user settings, which is much more stable than looking for the user's name somewhere in the page header:
app.steps.ts
import { expect } from '@playwright/test';import { Given, Then } from './fixtures';/** App names used in the features -> unique names of the model-driven apps */const apps: Record<string, string> = { 'Sales Hub': 'msdynce_saleshub',};Given('I open the {string} app', async ({ page }, app: string) => { const uniqueName = apps[app] ?? app; await page.goto(`/main.aspx?appname=${uniqueName}`); // Dataverse's error page has an Xrm object too: wait until the app itself reports that it is open await expect .poll( () => page.evaluate(async () => { try { return (await Xrm.Utility.getGlobalContext().getCurrentAppProperties()).uniqueName; } catch { return undefined; } }), { message: `The "${app}" app did not open` }, ) .toBe(uniqueName);});Then('I have the {string} security role', async ({ page }, role: string) => { const roles = await page.evaluate(() => Xrm.Utility.getGlobalContext() .userSettings.roles.get() .map((r) => r.name), ); expect(roles).toContain(role);});
Switching user in the middle of a scenario
Some processes need two people: a salesperson submits, a manager approves. Since Playwright 1.59, context.setStorageState() loads another session into the running browser, so one step can hand the scenario over:
switch-user.steps.ts
import { When } from './fixtures';import { authFile, isPersona } from '../auth/users';// Needs Playwright 1.59 or laterWhen('the {string} takes over', async ({ context, page }, persona: string) => { if (!isPersona(persona)) throw new Error(`Unknown persona "${persona}"`); await context.setStorageState(authFile(persona)); await page.reload();});
gherkin
When I submit the quote "Q-1001" for approvalAnd the "sales-manager" takes overThen the quote "Q-1001" is waiting for my approval
Running it
If one of your personas signs in interactively, start with the setup project in a visible browser and finish the sign-in yourself:
terminal
npx playwright test --project=setup --headed
From then on, for the next 8 hours, generate the tests from the features and run them as usual. The setup reuses the saved sessions:
terminal
npx bddgen && npx playwright test
In the pipeline, only the personas without a person behind them are configured: no MFA, TOTP or passkey. The interactive ones are skipped, together with their scenarios. Their passwords, TOTP secrets and passkeys come from secret variables. In part 2, coming soon, we write that pipeline and review the results in the Playwright BDD Report extension. We also let AI do a good part of the writing of features and steps.