WebUI OIDC with Microsoft Entra ID always fails: InvalidSignature because SPA only requests Graph scopes

Issue Description

Environment

  • Stalwart version: v0.16.26
  • OS: Debian 13.6 (amd64)
  • Directory type: Internal
  • Authentication directory: External OIDC (Microsoft Entra ID)

Description

When configuring an external OIDC directory pointing to Microsoft Entra ID (Azure AD),
WebUI authentication fails with JWT validation failed: InvalidSignature.

The root cause is that the Stalwart WebUI SPA requests only standard OpenID Connect
scopes (openid email profile offline_access) in the authorization request to Entra.
Microsoft Entra responds with an access token whose audience is Microsoft Graph
(aud: 00000003-0000-0000-c000-000000000000), not the registered application.
Graph API access tokens are signed with Microsoft-internal keys that are not published
in the tenant’s JWKS endpoint, making them impossible to verify by any third-party service.

Expected Behavior

The authorization request sent to the external OIDC provider should include a
configurable list of scopes. When the operator adds an application-specific scope
such as api://client-id/Stalwart.Access, Entra issues a JWT with aud = client-id,
signed with the tenant public JWKS keys, which Stalwart can verify successfully.

Alternatively, the Required Scopes field already present in the OIDC directory
configuration could be reused: those scopes should be appended to the outgoing
authorization request, not only used for incoming token validation.

Requested fix: please add a configuration field to the OIDC directory
(for example additionalScopes) that allows operators to specify extra scopes
to be appended to the authorization request sent to the external OIDC provider.
This is a minimal change that would make Stalwart work correctly with Microsoft
Entra ID, one of the most widely deployed enterprise identity providers.

Actual Behavior

The WebUI redirects correctly to Entra, the user authenticates successfully,
and the browser returns to /account/oauth/callback with the authorization code.
The SPA exchanges the code directly with Entra via PKCE, obtains an access token,
and sends it as a Bearer token to /jmap/session.

Stalwart responds with:
Authentication error: JWT validation failed: InvalidSignature
causedBy: directory/src/core/dispatch.rs line 19

Decoding the access token sent by the SPA to /jmap/session shows:
aud: 00000003-0000-0000-c000-000000000000 (Microsoft Graph)
iss: sts.windows.net / tenant issuer
appid: our registered client-id

The audience is Microsoft Graph, not the registered application.
The token is signed with Microsoft-internal keys not present in the public JWKS endpoint.

Root cause: the Stalwart WebUI SPA hardcodes the OAuth scope request to:
openid email profile offline_access

Microsoft Entra only issues a verifiable JWT with aud = client-id when at least one
application-specific scope is included in the authorization request, for example:
api://client-id/Stalwart.Access

Since no application-specific scope is requested, Entra always returns a Graph token
with an unverifiable signature, regardless of requestedAccessTokenVersion,
Required Audience configuration in Stalwart, or any other App Registration setting.

Reproduction Steps

  1. Install Stalwart v0.16.26 with internal directory.

  2. Create an App Registration in Microsoft Entra ID:

    • Supported account types: single tenant
    • Redirect URI type Web: hostname/
    • Redirect URI type SPA: hostname/account/oauth/callback
    • Expose an API: set Application ID URI to api://client-id
    • Add scope named Stalwart.Access
    • API permissions: openid, email, profile, User.Read (Graph delegated)
    • Grant admin consent
    • Manifest: set requestedAccessTokenVersion to 2
  3. In Stalwart WebUI, create an OIDC directory:

    • Issuer URL: Entra ID v2.0 OIDC endpoint for the tenant
    • Required Audience: client-id
    • Required Scopes: openid, email
    • Username Claim: preferred_username
    • Name Claim: name
  4. In Settings > Authentication > General, set Authentication Directory
    to the newly created OIDC directory.

  5. Open the WebUI account page in an incognito browser window.

  6. Enter a valid Entra user account and click Continue.

  7. Complete Microsoft authentication (password + MFA if enabled).

  8. Observe: browser returns to /account/oauth/callback, then immediately
    receives 401 Unauthorized from /jmap/session.

Relevant Log Output

Logging level set to Trace. Entries during a failed authentication attempt:

TRACE HTTP response body: Stalwart correctly fetches the Entra OIDC discovery
document including jwks_uri and userinfo_endpoint. Status 200.

ERROR Authentication error:
reason = “Token validation error: JWT validation failed: InvalidSignature”
causedBy = “crates/directory/src/core/dispatch.rs:19”
Token signature cannot be verified because the signing key is not in the
public JWKS endpoint (Graph token signed with internal Microsoft key).

Authorization request captured from browser Network tab shows:
response_type=code
scope=openid email profile offline_access
Only standard OIDC scopes are present. No application-specific scope is included.
This causes Entra to issue a Graph token instead of a verifiable application token.

Stalwart Version

v0.16.x

Installation Method

Binary (Linux)

Database Backend

RocksDB

Blob Storage

RocksDB

Search Engine

Internal

Directory Backend

OIDC

Additional Context

  • Stalwart deployed on internal DMZ network, not yet publicly exposed.
    Testing via local hosts file. Server has full outbound internet access
    and correctly reaches all Microsoft endpoints. Issue confirmed to be
    independent of public reachability.
  • No reverse proxy. Stalwart handles TLS directly with a wildcard
    Let’s Encrypt certificate.
  • Firewall: UFW active, ports 22 and 443 open inbound only.
  • Entra ID P1 license. Users synchronized from on-premise Active Directory
    via Entra Connect.
  • Test user exists in Entra without Exchange Online or M365 license.
    This is intentional: the use case is providing local mailboxes on Stalwart
    for occasional users without full M365 licenses, reusing corporate
    credentials and MFA policies via SSO.
  • This issue blocks a real-world enterprise deployment scenario where
    Microsoft Entra ID is the central identity provider and Stalwart
    is the self-hosted mail server.

I have reviewed the documentation and FAQ and confirm that my issue is NOT addressed there.

on

I have searched this support forum (open and closed topics) and confirm this is not a duplicate.

on

I understand that topics in this category are triaged by a bot first but a human reply will follow up. If I’d prefer a human-only reply, I’ll add the no-ai tag to my topic.

on

Current Stalwart OIDC directories do not have a field to customize the scopes requested in the WebUI’s own authorization request to the external OIDC provider. The requireScopes field on the Oidc directory object only validates the scopes present in an access token Stalwart receives — it is not fed back into the SPA’s outgoing OAuth authorization request, which only asks for openid email profile offline_access. Reviewing the WebUI source confirms the authorization scope list is driven by discovery data (stalwart_required_scopes / scopes_supported) returned from /api/discover, but the server’s discovery document does not currently expose an additional, operator‑configurable scope list for third‑party IdPs like Entra that mint a Microsoft Graph–audience token unless an app‑specific scope is requested.

So your diagnosis matches what’s in the code today: there is no additionalScopes-style setting to append an application-specific scope (e.g. api://client-id/Stalwart.Access) to the outgoing authorization request. This would need a product change on Stalwart’s side; a human maintainer will need to confirm if/when such a field will be added.

Reference: Stalwart Labs · GitHub (OIDC directory docs) OpenID Connect | Stalwart

This is an automated reply from the Stalwart Help Bot. Other community members may follow up if this answer is incomplete or wrong.

Entra hands out a Graph token whenever only the OIDC scopes are requested, and nothing outside Microsoft can verify those, so the Web UI can’t log in against it as it stands. The scopes it asks for are fixed when the Web UI is built, so on 0.16 the way to get this working is a custom build with the application scope added:

VITE_OAUTH_SCOPES="openid email profile offline_access api://<client-id>/Stalwart.Access"

On the directory, set requireAudience to your client id and empty requireScopes. Entra puts scopes in the scp claim, which 0.16 doesn’t read, so the default requireScopes would reject the token even with the right audience. Both fields are in the OIDC directory docs.

About your request for a configurable extra scope on the directory. Yes, we could do that, but it won’t help the fact that Entra is not compatible with the new OAuth Public draft. Once that is published you won’t be able to use Apple Mail and other clients with Entra and there is nothing that Stalwart can do to help as the mail client will authenticate against Entra directly.

Thank you for the guidance. We followed both steps exactly.

**Step 1 - Custom WebUI build**

We cloned the webui repository, created a .env.production file with:

VITE_OAUTH_SCOPES=openid email profile offline_access api://\*\*\*\*\*\*\*\*++++e/Stalwart.Access

Built with npm ci && npm run build, packaged as webui.zip, and loaded it

into Stalwart via Settings > Telemetry > Web Applications > Resource URL

set to file:///etc/stalwart/webui-custom.zip.

Confirmed the new WebUI is active - the authorization request to Entra now

includes the application scope:

scope=openid+email+profile+offline_access+api%3A%2F%\*\*\*\*\*\*\*\*\*+++++6e%2FStalwart.Access

**Step 2 - Directory configuration**

Updated the OIDC directory:

- requireAudience: 5*********

- requireScopes: cleared (empty)

**Current result**

The error has changed. Before it was:

API error 401: Unauthorized

Now it shows:

Your session has expired. Please sign in again.

No new entries appear in the Stalwart log during the login attempt,

suggesting the request does not reach the server-side authentication layer.

The authorization flow completes correctly in the browser (redirect to Entra,

authentication, return to /account/oauth/callback with code). After that the

WebUI shows the session expired message without any error logged on the server.

Could you advise what the “session expired” message indicates in this context

and what to check next?

“Your session has expired” is the Web UI’s way of saying /jmap/session answered 401 and a token refresh didn’t fix it, so the custom build is doing its job and the token now reaches the server. What’s left is the server still rejecting it, and the fact that nothing shows in the log narrows it down. A bad signature, issuer or audience is logged as an error, as you saw before. The quiet rejections are a missing required scope, no usable email claim in the token, or userinfo refusing the token, and those are logged at debug level.

Directory changes only take effect after a settings reload, so if you saved the directory without running Management › Actions › Reload settings (or restarting), the old requireScopes is still active and will reject every Entra token. That’s the first thing I’d rule out. If it still fails after the reload, set logging to debug for one attempt and post the auth.failed line. Also decode the new access token (jwt.ms works) and post iss, aud, ver, scp and preferred_username with the identifiers redacted. ver should be 2, iss has to match the v2.0 issuer exactly, and aud has to equal requireAudience, which in a v2 token is the bare client id GUID, not the api:// URI.