Add Sign-in to Your Workbench
Goal: Let only the people and jobs your App Identity signs in call your workbench.
Your workbench checks its own callers. OpenX does not sign anyone in for it: a call through OpenX's address
reaches the mode with OpenX's own credentials taken off, and the workbench decides. In front of an Identity
mode, OpenX's address answers 403 until App Identity registers the mode's app (and, for a mode set before
workbenches checked their own callers, until a person confirms it), and then forwards only a bearer issued for
that app (Through OpenX's address). A mode set to None gets no login settings and
no check from OpenX, so it must check its own callers. OpenX also hands each mode linked to your
App Identity its login settings, as a plain setting, so your code knows
which directories to trust. There is no fAI helper to add: you use a standard library for your language, as below.
The login settings
A mode is linked to App Identity when Who may call this mode, in the inspector's Modes tab, is
Identity. On its next Deploy, OpenX sets FATHYM_OX_WORKBENCH_LOGINS in its container: a JSON list with one
entry for each directory the mode is linked to (every directory of the workspace, unless the mode names some).
[
{ "Kind": "workforce", "Issuer": "https://login.microsoftonline.com/<tenant id>/v2.0" },
{ "Kind": "b2c", "Issuer": "https://<domain>/<tenant id>/<policy>/v2.0" }
]
Kindis the login system:workforcefor a company directory (Microsoft Entra),b2cfor Azure AD B2C.Issueris where the directory's discovery document lives:<Issuer>/.well-known/openid-configuration. The document gives the issuer a token carries and the address of the keys that sign it.- Nothing in it is secret, and OpenX's own sign-in is never in it.
- A mode set to None gets no login settings. Neither does a mode linked to no directory.
- A Deploy that cannot name a linked directory's issuer stops before it builds anything, with
WORKBENCH_LOGIN_INCOMPLETE: finish that directory in App Identity, or untick it for the mode.
Check a caller
For every call, before the workbench does anything else:
- Read the bearer token from the
Authorizationheader. No token: refuse with401. - Find the listed directory whose discovery document names the token's issuer. None: refuse.
- Check the token with that directory's keys: its signature, its issuer, that it has not expired, and that its audience is your app's id (The app id). Anything wrong: refuse.
Read each discovery document once and keep its keys; a good library fetches new keys when the directory rolls
them. Never compare a token's issuer with the listed Issuer: for Azure AD B2C they differ (below).
Accept access tokens only, never ID tokens. An ID token tells an app who signed in; it is not meant to be sent to an API. It is issued to the app that signed the person in, so its audience can pass a check that only compares the audience. Check the token's type, or make sure the audience is your API's app id and not a client's: give the workbench its own app, as The app id does, and no client's ID token carries that audience.
The app id
A directory signs tokens for many apps. The audience a token carries says which app it was issued for, and your workbench admits only tokens issued for its own app: its app id, the app's client id in that directory.
The app id comes with the app's registration: App Identity will register an app for each linked mode in the
mode's directory and hand its id to the mode. That registration is coming, and is not built yet. Until it is,
register an app for the mode yourself in the directory and set its client id as an Environment value,
WORKBENCH_APP_ID, as the samples below read it.
NO APP ID, NO CALLERS
With no app id the samples refuse every caller. Without one the audience cannot be checked, and a token the
directory issued to any other app in it would pass; in Azure AD B2C anyone can sign up to some app. Set
WORKBENCH_APP_ID before you expect anyone to get in.
Through OpenX's address
Setting WORKBENCH_APP_ID lets callers in at the workbench's own address. It does not open OpenX's address
(/ox-api/w/<workspace id>/workbenches/...) to an Identity mode:
- Until App Identity registers the mode's app, OpenX answers every call to an Identity mode
403WORKBENCH_LOGIN_NOT_REGISTERED, whatever token it carries. Meanwhile, call the mode at its container's own address with a token for yourWORKBENCH_APP_ID(How a workbench secures itself), or set it to None if the workbench signs its callers in some other way. - Once the mode's app is registered, OpenX passes a caller's own token on to the mode only when it was issued for that app. Any other token, a team key from APIs -> API Keys, and your OpenX sign-in are taken off on the way.
- A mode set to Identity before workbenches checked their own callers also needs a person to confirm, in its
inspector's Modes tab, that the workbench checks its own callers. Until then OpenX answers it
403WORKBENCH_SIGN_IN_UNCONFIRMED, and its own address stays closed too.
Microsoft Entra (company directory)
The entry's Kind is workforce, and its Issuer is the directory's v2.0 authority:
[{ "Kind": "workforce", "Issuer": "https://login.microsoftonline.com/<tenant id>/v2.0" }]
- Discovery:
https://login.microsoftonline.com/<tenant id>/v2.0/.well-known/openid-configuration. Itsissueris the same address as the listed one. - A caller signs in to the directory and asks for a scope your app's registration exposes (Expose an API). The token's audience is then your app id.
- Ask for v2.0 tokens. Entra issues an app's access tokens in the older v1.0 form unless its registration asks
for v2.0: in the app's manifest, set
requestedAccessTokenVersionto2. A v1.0 token's issuer ishttps://sts.windows.net/<tenant id>/, which no discovery document above names, so the check refuses it.
Azure AD B2C (customer directory)
The entry's Kind is b2c, and its Issuer is the authority of the directory's sign-in policy (user flow):
[{ "Kind": "b2c", "Issuer": "https://<domain>/<tenant id>/<policy>/v2.0" }]
- Discovery:
https://<domain>/<tenant id>/<policy>/v2.0/.well-known/openid-configuration. - A token's issuer has no policy in it: by default it is
https://<domain>/<tenant id>/v2.0/, with a closing slash. That is theissuerthe discovery document names, so read it from there. A check that compares the token with the listedIssuerrefuses every B2C caller. - A caller signs in through the policy and asks for a scope your app exposes. The token's audience is your app id.
- Policies (user flows) in one tenant can share an issuer, so a token from any of them passes an issuer check
that names only one. Pin the policy you expect too: check the token's
tfpclaim (older tokens carry the policy inacr) names it.
TypeScript (Deno)
Add the one library: deno add jsr:@panva/jose. Then:
import {
createRemoteJWKSet,
customFetch,
decodeJwt,
type JWTPayload,
jwtVerify,
type JWTVerifyGetKey,
} from '@panva/jose';
/** One login system a mode linked to App Identity is handed: its kind and its issuer. */
export type Login = { Kind: string; Issuer: string };
/**
* The login settings OpenX hands a mode linked to App Identity, in FATHYM_OX_WORKBENCH_LOGINS: a
* JSON list with one { Kind, Issuer } per directory. Anything else reads as no login system.
*/
export function readLogins(raw: string | undefined): Login[] {
try {
const list: unknown = JSON.parse(raw ?? '[]');
return Array.isArray(list)
? list.filter((l): l is Login => typeof l?.Issuer === 'string' && l.Issuer !== '')
: [];
} catch {
return [];
}
}
/**
* Checks a caller's bearer token against the login systems. Each listed Issuer is where its
* directory's discovery document lives. A token's `iss` is that document's `issuer`, which for
* Azure AD B2C is not the listed Issuer, so it is read from the document.
*
* With no app id every caller is refused, before any directory is read. Without one the audience
* cannot be checked, and a token the directory issued to any other app would pass; in a B2C
* directory anyone can sign up to some app. The app id comes with the app's registration, which
* OpenX does not hand yet; until it does, register an app yourself and set its id in
* WORKBENCH_APP_ID.
*/
export function CallerCheck(
logins: Login[],
appId: string | undefined,
fetcher: typeof fetch = fetch,
) {
const trusted = new Map<string, Promise<{ Issuer: string; Keys: JWTVerifyGetKey }>>();
function trust(login: Login) {
let found = trusted.get(login.Issuer);
if (!found) {
found = fetcher(`${login.Issuer.replace(/\/+$/, '')}/.well-known/openid-configuration`)
.then((res) => {
if (!res.ok) throw new Error(`Discovery answered ${res.status}.`);
return res.json();
})
.then((doc: { issuer: string; jwks_uri: string }) => ({
Issuer: doc.issuer,
Keys: createRemoteJWKSet(new URL(doc.jwks_uri), { [customFetch]: fetcher }),
}));
// A directory that could not be read is read again on the next call.
found.catch(() => trusted.delete(login.Issuer));
trusted.set(login.Issuer, found);
}
return found;
}
return {
/** The caller's checked claims, or undefined: no app id, no bearer, an unlisted issuer, a bad token. */
async Caller(req: Request): Promise<JWTPayload | undefined> {
if (!appId) return undefined;
const token = req.headers.get('Authorization')?.match(/^Bearer\s+(\S+)$/i)?.[1];
if (!token) return undefined;
let iss: string | undefined;
try {
iss = decodeJwt(token).iss;
} catch {
return undefined;
}
for (const login of logins) {
const known = await trust(login).catch(() => undefined);
if (!known || known.Issuer !== iss) continue;
try {
const { payload } = await jwtVerify(token, known.Keys, {
issuer: known.Issuer,
audience: appId,
algorithms: ['RS256'],
requiredClaims: ['exp'],
});
return payload;
} catch {
// Not a good token from this login system; try the next one.
}
}
return undefined;
},
};
}
// OpenX hands these login settings to a mode linked to App Identity. Through OpenX's address it
// forwards only a bearer issued for the mode's app, and answers 403 until that app is registered
// and confirmed. A mode set to None gets no login settings and no check from OpenX: this is its
// only check.
const check = CallerCheck(
readLogins(Deno.env.get('FATHYM_OX_WORKBENCH_LOGINS')),
Deno.env.get('WORKBENCH_APP_ID'),
);
In your handler, call await check.Caller(req) first, and answer 401 when it returns nothing; otherwise it
returns the caller's checked claims (sub names the caller). The fetcher parameter lets a test serve the
discovery documents and keys itself; a workbench leaves it out. This is the check the
relay workbench runs, in a whole Web mode you can host.
C# (.NET)
An ASP.NET Core minimal API (Microsoft.NET.Sdk.Web) with two packages:
dotnet add package Microsoft.IdentityModel.Protocols.OpenIdConnect and
dotnet add package Microsoft.IdentityModel.JsonWebTokens.
using System.Text.Json;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
// OpenX hands these login settings to a mode linked to App Identity. Through OpenX's address it
// forwards only a bearer issued for the mode's app, and answers 403 until that app is registered
// and confirmed. A mode set to None gets no login settings and no check from OpenX: this is its
// only check.
var logins = JsonSerializer.Deserialize<Login[]>(
Environment.GetEnvironmentVariable("FATHYM_OX_WORKBENCH_LOGINS") ?? "[]") ?? [];
// The app id comes with the app's registration, which OpenX does not hand yet; until it does,
// register an app yourself and set its id. With no app id every caller is refused.
var appId = Environment.GetEnvironmentVariable("WORKBENCH_APP_ID");
// One discovery reader per login system: it reads the document once and keeps its keys.
var directories = logins
.Where(login => !string.IsNullOrEmpty(login.Issuer))
.Select(login => new ConfigurationManager<OpenIdConnectConfiguration>(
$"{login.Issuer.TrimEnd('/')}/.well-known/openid-configuration",
new OpenIdConnectConfigurationRetriever()))
.ToList();
var tokens = new JsonWebTokenHandler();
async Task<bool> IsSignedIn(HttpRequest req)
{
// Without an app id the audience cannot be checked, so no caller passes.
if (string.IsNullOrEmpty(appId)) return false;
var header = req.Headers.Authorization.ToString();
if (!header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) return false;
foreach (var directory in directories)
{
OpenIdConnectConfiguration discovered;
try { discovered = await directory.GetConfigurationAsync(); }
catch { continue; }
var result = await tokens.ValidateTokenAsync(header["Bearer ".Length..].Trim(),
new TokenValidationParameters
{
// A token's issuer is the discovery document's, which for B2C is not the listed Issuer.
ValidIssuer = discovered.Issuer,
IssuerSigningKeys = discovered.SigningKeys,
ValidAlgorithms = ["RS256"],
ValidAudience = appId,
ValidateAudience = true,
});
if (result.IsValid) return true;
}
return false;
}
var app = WebApplication.Create(args);
app.MapPost("/send", async (HttpRequest req) =>
await IsSignedIn(req) ? Results.Accepted() : Results.Unauthorized());
app.Run();
record Login(string Kind, string Issuer);
ConfigurationManager refreshes the keys when the directory rolls them, and the handler checks the expiry
itself.
If something's off
| Issue | Do |
|---|---|
Every caller gets 401 | Check WORKBENCH_APP_ID is set: with no app id the samples refuse everyone. Then check the mode is Identity and was deployed since, so it has FATHYM_OX_WORKBENCH_LOGINS. A mode set to None has none |
OpenX's address answers 403 WORKBENCH_LOGIN_NOT_REGISTERED | The mode is Identity and App Identity has not registered its app yet; that registration is coming. Until then call the mode at its own address, or set it to None (Through OpenX's address) |
OpenX's address answers 403 WORKBENCH_SIGN_IN_UNCONFIRMED | The mode was set to Identity before workbenches checked their own callers. Confirm, in its inspector's Modes tab, that the workbench checks its own callers, and deploy again |
Every company-directory caller gets 401 | The tokens are v1.0. Set requestedAccessTokenVersion to 2 in the app's manifest, and sign in again |
Every B2C caller gets 401 | The check compares the token's issuer with the listed Issuer. Read the issuer from the discovery document instead |
A caller with a good token gets 401 | The token was issued for another app: its audience is not your WORKBENCH_APP_ID |
Deploy stops with WORKBENCH_LOGIN_INCOMPLETE | A directory the mode is linked to is not finished in App Identity. Finish it, or untick it for the mode, and deploy again |
Next steps
- Where the directories come from -> App Identity
- A whole Web mode that checks its callers -> Build a relay workbench
- The addresses and what reaches a mode -> Reach a Hosted Workbench
On fathym.com: Workbenches →