Command-line tools often authenticate in awkward ways: a long-lived secret in an environment variable, a token pasted from a portal, or a browser tab on every run. On Windows there is a better option. If the user has already signed in with a work account, the Web Account Manager (WAM) broker can issue tokens to your app, often with no prompt at all.

This article walks through a small proof of concept:

  • a .NET 10 Minimal API that accepts only valid Entra ID access tokens,
  • a mycli.exe that gets those tokens through WAM, and
  • Terraform that creates both app registrations.

The full source is at github.com/darkedges/entraid-wam-cli.

The design

 mycli.exe ──(1) token request──▶ WAM broker ──(2) uses PRT──▶ Microsoft Entra ID │ ◀────────(3) access token────────────────────────────────┘ │ └──(4) GET /api/me, Authorization: Bearer ...──▶ API ──(5) signing keys──▶ Entra ID 

The Primary Refresh Token (PRT) is the credential Windows holds for single sign-on. The important design point is that the CLI never reads or handles it. The app asks the broker for an access token for one scope, and that is all it receives.

Decisions worth calling out:

Decision Reason
Two app registrations The API defines a permission; the CLI is a client that requests it
CLI is a public client An executable on a user's machine cannot keep a secret
One delegated scope, access_as_user The API acts for a signed-in user, not as a daemon
Single tenant, v2 tokens One predictable issuer and audience to validate

Why .NET

I first looked at Go. At the time of writing, the MSAL Go documentation I checked (v1.10.1) showed no broker option, and WAM was the point of the exercise. MSAL.NET supports it directly and still produces a single .exe. I used .NET 10 because .NET 8 reached end of support in November 2026.

The API

The JWT bearer handler does the heavy lifting. Pointing it at the tenant's OpenID Connect metadata gives you signing key retrieval, caching and rollover.

options.MetadataAddress = $"{authority}/.well-known/openid-configuration"; options.MapInboundClaims = false; // keep "scp", "oid", "name" as issued options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = authority, // https://login.microsoftonline.com/{tenant}/v2.0 ValidateAudience = true, ValidAudiences = [clientId, $"api://{clientId}"], ValidateLifetime = true, RequireExpirationTime = true, ValidateIssuerSigningKey = true, RequireSignedTokens = true, ValidAlgorithms = [SecurityAlgorithms.RsaSha256], ClockSkew = TimeSpan.FromMinutes(1), NameClaimType = "name", }; 

A valid token is not enough: it also needs the scope. scp is a space-separated string, so split it and match whole entries. A substring check would accept access_as_user_extra.

static bool HasScope(ClaimsPrincipal user, string scope) => user.FindAll("scp") .SelectMany(c => c.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries)) .Contains(scope, StringComparer.Ordinal); 

A bad or missing token returns 401. A good token without the scope returns 403.

The CLI

Turning on the broker

You need the Microsoft.Identity.Client.Broker package and a net10.0-windows target.

var app = PublicClientApplicationBuilder .Create(config.ClientId) .WithAuthority(AzureCloudInstance.AzurePublic, config.TenantId) .WithDefaultRedirectUri() .WithParentActivityOrWindow(WindowHandle.ForConsole) .WithBroker(new BrokerOptions(BrokerOptions.OperatingSystems.Windows) { Title = "mycli" }) .Build(); 

Parenting the dialog in a terminal

WAM needs a window to own its dialog. Under Windows Terminal, GetConsoleWindow() returns a hidden pseudo-window, so ask for its root owner:

var console = GetConsoleWindow(); if (console == IntPtr.Zero) return GetForegroundWindow(); var owner = GetAncestor(console, 3 /* GA_ROOTOWNER */); return owner != IntPtr.Zero ? owner : console; 

Silent first

The order is: the account MSAL already cached, then the Windows account, then a dialog.

return await app.AcquireTokenSilent(scopes, PublicClientApplication.OperatingSystemAccount) .ExecuteAsync(cancellationToken); 

Only MsalUiRequiredException leads to the interactive path. Other failures are reported, because opening a dialog would not fix a misconfiguration. The MSAL token cache is persisted with Microsoft.Identity.Client.Extensions.Msal, which protects it with DPAPI on Windows.

Letting the user choose an account

Silent sign-in worked a little too well. The CLI picked up the account I had used to run Terraform, with no chance to choose another. The fix was a --select-account option:

var picked = await _app.AcquireTokenInteractive(_scopes) .WithPrompt(Prompt.SelectAccount) .ExecuteAsync(cancellationToken); 

Showing the picker is only half of it. The CLI also stores the chosen account's ID and uses only that account afterwards. Without this, a later run could quietly drift back to the default Windows account.

Protecting the token on the way out

  • The API URL must be HTTPS, unless it is localhost.
  • HTTP redirects are disabled.
  • The config file is read from the exe's folder, never the current directory, so running the tool inside an untrusted folder cannot redirect your token.
  • Tokens are never printed.

Shipping one file

<RuntimeIdentifier>win-x64</RuntimeIdentifier> <SelfContained>true</SelfContained> <PublishSingleFile>true</PublishSingleFile> <IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract> 

The last line matters because the broker depends on a native library, msalruntime.dll.

App registrations with Terraform

Both registrations have a value that contains their own client ID, which does not exist until the app is created:

  • the API's identifier URI, api://{client_id}
  • the CLI's broker redirect URI, ms-appx-web://microsoft.aad.brokerplugin/{client_id}

The azuread provider has separate resources for these, which avoids a self-reference:

resource "azuread_application_identifier_uri" "api" { application_id = azuread_application.api.id identifier_uri = "api://${azuread_application.api.client_id}" } resource "azuread_application_redirect_uris" "cli_broker" { application_id = azuread_application.cli.id type = "PublicClient" redirect_uris = ["ms-appx-web://microsoft.aad.brokerplugin/${azuread_application.cli.client_id}"] } 

The parent azuread_application resources need ignore_changes for those attributes so the two do not fight.

On the API app, do not miss this:

api { requested_access_token_version = 2 } 

Without it you get v1 tokens, issued by sts.windows.net, and an API expecting the v2 issuer rejects them all.

The configuration also grants admin consent, because a silent request cannot show a consent screen, and can optionally limit sign-in to named users.

Running it

az login --tenant <TENANT_ID> --allow-no-subscriptions Copy-Item infra\terraform.tfvars.example infra\terraform.tfvars # set tenant_id terraform -chdir=infra init terraform -chdir=infra plan -out tfplan terraform -chdir=infra apply tfplan terraform -chdir=infra output -raw api_env | Set-Content api\.env New-Item -ItemType Directory -Force publish | Out-Null terraform -chdir=infra output -raw mycli_json | Set-Content publish\mycli.json dotnet run --project api # terminal 1 dotnet publish cli -c Release -o publish # terminal 2 .\publish\mycli.exe whoami 

Device state changes the experience

Run dsregcmd /status before you judge the behaviour.

Device Typical signs What to expect
Entra joined or hybrid joined AzureAdJoined : YES, AzureAdPrt : YES Silent sign-in with the Windows account
Entra registered WorkplaceJoined : YES, AzureAdPrt may be NO A prompt is possible
Neither All NO A sign-in dialog

My machine is registered, not joined, and the CLI still signed in without prompting. I have not yet tested a joined device, and your tenant's Conditional Access policies may change the outcome.

Testing

Integration tests replace only the signing key source with a locally generated RSA key. Every validation rule stays as shipped. They cover a valid token, no token, expired, wrong audience, wrong issuer, wrong key and missing scope.

var metadata = new OpenIdConnectConfiguration { Issuer = Issuer }; metadata.SigningKeys.Add(_key); options.ConfigurationManager = new StaticConfigurationManager<OpenIdConnectConfiguration>(metadata); 

These tests say nothing about WAM or the PRT. Those need a real device and tenant.

Gotchas

Symptom Cause
Every call returns 401 v1 tokens, or a tenant or client ID mismatch
AADSTS50011 Broker redirect URI missing or wrong
AADSTS7000218 Redirect URI added as Web, not Mobile and desktop applications
AADSTS65001 Consent not granted
404 from your own /health Something else owns the port. For me, Docker/WSL held 5000

What it still needs before production

  • HTTPS and a real host for the API
  • Authorization beyond the scope: app roles, groups, or checking which client called (azp)
  • Rate limiting, logging and monitoring
  • A code-signed executable, installed somewhere ordinary users cannot modify
  • A CI pipeline and remote Terraform state
  • Testing on joined devices and under your Conditional Access policies

Wrapping up

The amount of authentication code here is small, and that is the point. The broker handles the credential, MSAL handles the protocol, and the JWT handler handles validation. Your job is mostly to configure them precisely and to be careful about where the token goes.

This project and article were drafted with the help of an AI assistant (Claude).