Morten Sæther

← Blog

Advanced Security & Authentication

#19 · 25 June 2026

MFA, custom auth flows, RBAC, and knowing when something's gone wrong

Basic authentication answers one question: is this person who they say they are? Enterprise portals need more - which of the several ways did they prove it, what exactly are they allowed to touch, and would you notice if someone else was using their session right now.

This post covers the layers that sit on top of the login box.

Step by step

One rule sits under everything here. The portal session is created when the sign-in completes, either through an identity provider or a local account, and nothing in page code can make Power Pages treat a user as more authenticated than that sign-in did. A JavaScript class that checks a code afterwards is a UI gate, and a UI gate is skipped by not running the JavaScript. So MFA, SSO and permissions are all configured, not coded, and the code in this post is what sits on top of that configuration.

1. Multi-factor authentication

MFA belongs to the identity provider. For an OpenID Connect provider the portal can ask for it: create the site setting Authentication/OpenIdConnect/{ProviderName}/AcrValues with the value your provider expects, and Power Pages includes the acr_values parameter in the authorization request. The provider enforces the assurance level and only returns an ID token once the user has passed. Most providers can also require MFA for the portal’s app registration in their own policy, which works without the portal knowing about it.

The provider name is the one in your existing site settings, for example OpenId_1 in Authentication/OpenIdConnect/OpenId_1/Issuer, not the display name on the sign-in button.

Local accounts have the built-in email second factor:

Site setting What it does Default
Authentication/Registration/TwoFactorEnabled Lets users with a confirmed email address opt in to an emailed security code False
Authentication/Registration/RememberBrowserEnabled Offers a “Remember browser?” option so the code is not required on the next sign-in from the same browser True
Authentication/TwoFactorCookie/ExpireTimeSpan How long the two-factor cookie stays valid; should not exceed six minutes 5 minutes

Microsoft recommends retiring local accounts in favour of an external provider, so treat this as the fallback, not the design.

Passkeys, security keys and biometrics are the provider’s feature too. The portal never sees a fingerprint, a face or a stored template; it sees an ID token that says the user passed. The part the portal owns is getting the user to the right provider:

<!-- Send the user straight to the work-account provider -->
<a class="btn btn-primary"
   href="/Account/Login/ExternalLogin?ReturnUrl={{ request.path_and_query | url_escape }}&provider=OpenId_1">
    {{ snippets['security.login.work_account'] | default: 'Sign in with your work account' }}
</a>

If one provider handles all sign-ins, set Authentication/Registration/LoginButtonAuthenticationType to its authentication type and the Sign In button skips the provider chooser altogether.

Get the fallback right. MFA that locks out legitimate users when their phone dies just moves the problem to your support queue, and the recovery path lives with the provider as well.

2. Custom authentication flows

Enterprise SSO, for when the organisation already has an identity provider and no interest in another password. Power Pages has built-in support for Microsoft Entra ID, Entra ID with multiple tenants and Entra External ID, and takes any other OpenID Connect provider through Security > Identity providers > New provider > Other > OpenID Connect. SAML 2.0 and WS-Federation are supported for the organisations that still speak them.

The provider configuration is a set of site settings, written for you by the identity provider page:

Setting What goes in it
Authority The issuer URL, for Entra ID https://login.microsoftonline.com/<tenant ID>/
Client ID The application ID from the app registration
Redirect URL The portal’s reply URL, exactly as registered with the provider
Metadata address The provider’s OpenID Connect metadata document URL
Scope openid is mandatory; add email and profile for the claims you want
Response type Default code id_token; code requires the client secret and response mode query
Client secret Required when the response type is code
External logout Signs the user out of the provider too, not only the portal

Two settings do the work that a custom callback handler would otherwise do. Registration claims mapping copies claims such as given_name, family_name and email into the contact record the first time a user signs in; login claims mapping refreshes them on every sign-in. Claims that are not in the ID token can come from the provider’s UserInfo endpoint, with Authentication/OpenIdConnect/{ProviderName}/UseUserInfoEndpointforClaims set to true and the mapping written as fieldName = userinfo.claimName.

What claims mapping does not do is assign web roles. A groups claim from the provider does not become a web role by itself; web roles are assigned to the contact in Dataverse, and if you want that automated it is a flow on the contact, not something the sign-in does.

Token validation is also the platform’s job. Issuer and audience validation are additional settings on the provider, with wildcard issuer filters for multi-tenant setups, and nonce validation is on by default. There is no SAML assertion parser or JWT validator to write; if you find yourself writing one in the browser, the token has already gone somewhere it should not be.

3. Role-based access control

Permissions in Power Pages are three layers, all evaluated on the server for every request:

The same table permissions apply to lists, forms, Liquid and every /_api call, so there is nothing to cache and no permission engine to build. What page code does is decide what to draw:

{% assign is_case_manager = user | has_role: 'Case Managers' %}

{% if is_case_manager %}
    <a href="/cases/new" class="btn btn-primary">New case</a>
{% endif %}

{% assign case = entities.incident[request.params.id] %}

{% if case and case.permissions.can_read %}
    <h2>{{ case.title | escape }}</h2>
    <p>{{ case.description | escape }}</p>

    {% if case.permissions.can_write %}
        <a href="/cases/edit?id={{ case.id }}" class="btn btn-outline-primary">Edit</a>
    {% endif %}
{% else %}
    <p>{{ snippets['cases.not_found'] | default: 'This case is not available.' }}</p>
{% endif %}

case.permissions is the table permission result for that record: can_read, can_write, can_create, can_delete, can_append, can_append_to, plus rules_exist, which tells you whether any rule applied at all. The escape filter stays on anything a user typed; title and description come from a form someone filled in.

On the JavaScript side, honour the answer the server gives rather than predicting it:

<div id="case-actions" data-case-id="{{ request.params.id | escape }}">
    <button type="button" class="btn btn-outline-danger" data-action="cancel">Cancel case</button>
    <p class="action-feedback" aria-live="polite"></p>
</div>

<script>
    // Needs Webapi/incident/enabled = true and
    // Webapi/incident/fields = statecode,statuscode
    function getToken() {
        return new Promise((resolve, reject) => {
            shell.getTokenDeferred().done(resolve).fail(reject);
        });
    }

    async function portalApi(path, options = {}) {
        const token = await getToken();
        const response = await fetch(`/_api${path}`, {
            ...options,
            credentials: 'same-origin',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                '__RequestVerificationToken': token,
                ...(options.headers || {})
            }
        });

        if (response.status === 401) {
            throw new Error('Your session has ended. Sign in again.');
        }
        if (response.status === 403) {
            throw new Error('You do not have permission to do that.');
        }
        if (!response.ok) {
            throw new Error(`Request failed (${response.status}).`);
        }

        return response.status === 204 ? null : response.json();
    }

    document.getElementById('case-actions').addEventListener('click', async function (event) {
        const button = event.target.closest('button[data-action="cancel"]');
        if (!button) return;

        const feedback = this.querySelector('.action-feedback');
        button.disabled = true;

        try {
            await portalApi(`/incidents(${this.dataset.caseId})`, {
                method: 'PATCH',
                body: JSON.stringify({ statecode: 2, statuscode: 6 })
            });
            feedback.textContent = 'Case cancelled.';
        } catch (error) {
            feedback.textContent = error.message;
            button.disabled = false;
        }
    });
</script>

A 403 is the permission model doing its job, and textContent keeps whatever comes back from being interpreted as markup. What this leaves out is conditions such as time of day or IP range; those are identity provider policies, not portal permissions.

What this looks like in practice

An account security page for the signed-in user, pulling it together. The numbers come from the contact record, where the portal writes them:

<!-- account-security.html -->
{% if user %}
<div class="security-dashboard">
    <h2>{{ snippets['security.page.title'] | default: 'Account security' }}</h2>

    <div class="security-metrics">
        <div class="metric-card">
            <div class="metric-value">{{ user.adx_identity_lastsuccessfullogin | date: 'g' }}</div>
            <div class="metric-label">Last successful sign-in</div>
        </div>

        <div class="metric-card">
            <div class="metric-value">{{ user.adx_identity_accessfailedcount | default: 0 }}</div>
            <div class="metric-label">Failed sign-in attempts since last success</div>
        </div>

        <div class="metric-card">
            {% if user.adx_identity_lockoutenddate %}
                <div class="metric-value warning">{{ user.adx_identity_lockoutenddate | date: 'g' }}</div>
                <div class="metric-label">Locked out until</div>
            {% else %}
                <div class="metric-value">Not locked</div>
                <div class="metric-label">Lockout status</div>
            {% endif %}
        </div>
    </div>

    <div class="auth-methods-status">
        <h3>Your access</h3>
        <ul>
            <li>Signed in as {{ user.fullname | escape }} ({{ user.emailaddress1 | escape }})</li>
            <li>Roles: {{ user.roles | join: ', ' | escape }}</li>
        </ul>
        <a href="/profile" class="btn btn-outline-primary">Manage sign-in methods</a>
    </div>

    <div class="security-settings">
        <h3>How this site is configured</h3>
        <table class="table">
            <tbody>
                <tr>
                    <td>Failed attempts before lockout</td>
                    <td>{{ settings['Authentication/UserManager/MaxFailedAccessAttemptsBeforeLockout'] | default: 5 }}</td>
                </tr>
                <tr>
                    <td>Lockout duration</td>
                    <td>{{ settings['Authentication/UserManager/DefaultAccountLockoutTimeSpan'] | default: '24:00:00' }}</td>
                </tr>
                <tr>
                    <td>Session cookie lifetime</td>
                    <td>{{ settings['Authentication/ApplicationCookie/ExpireTimeSpan'] | default: '24:00:00' }}</td>
                </tr>
                <tr>
                    <td>Email second factor for local accounts</td>
                    <td>{{ settings['Authentication/Registration/TwoFactorEnabled'] | default: 'false' }}</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
{% else %}
    <p><a href="{{ website.sign_in_url_substitution }}">Sign in</a> to see your account security.</p>
{% endif %}

adx_identity_lastsuccessfullogin, adx_identity_accessfailedcount and adx_identity_lockoutenddate are columns on the contact table, and user is the contact, so Liquid reads them directly. The date filter takes a .NET format string; 'g' is the short date and time. The profile page is where users confirm their email, connect external identities and turn on the email second factor.

What this leaves out is the site-wide view: active sessions, failed logins across all users, threat alerts. The portal has no endpoint for those. Web API calls are recorded in the Office 365 audit log when audit logging is enabled, and site-wide sign-in failures are a query against the contact table from a flow or a report, not a live stream into a page.

How to make a mess and fix it

  1. Auth flow breaking mid-way - check the reply URL, the metadata address and the response type against the app registration, in that order
  2. MFA problems - confirm the AcrValues site setting matches what the provider expects, and test the provider’s recovery path
  3. RBAC surprises - a 403 from /_api means a table permission is missing for that role and scope; the Liquid check only hides the button
  4. SSO provider conflicts - two providers for the same users means two contacts unless contact mapping with email is on
  5. Blind spots in monitoring - if there’s no audit trail, you’ll find out about incidents from someone else

Five habits worth keeping

  1. Defence in depth - no single control should be load-bearing
  2. Verify every request, regardless of where it came from
  3. Audit and pen-test regularly, not just before launch
  4. Have an incident procedure written down before you need it
  5. Monitor continuously - detection time is most of the damage

Wrapping up

Good security here is invisible to legitimate users and immovable for everyone else. Layer your controls, keep the audit trail, and design the recovery paths as carefully as the happy path - that’s where most lockouts happen.

Next: performance optimisation and monitoring, and making all of this fast.