Sign-in and consent screens
Build the login, consent, and account screens that the authorize endpoint redirects to.
When a client sends a user to /oauth2/authorize, Entro Auth redirects the user through pages you host: login, optional account steps, and consent.
How the redirect works
To stop anyone from changing the authorize parameters while the user moves through your pages, each redirect carries the original parameters as a signed query. Your pages pass it back as oauth_query, and Entro Auth verifies it before resuming. A query that was changed or has expired fails with an invalid_signature error. For example, a query with a different redirect_uri fails. The signature covers every authorize parameter, including custom ones, and expires after codeExpiresIn (10 minutes by default).
The oauthProviderClient plugin adds oauth_query to a request, other than GET and DELETE, only when the page URL carries a signed OAuth query. It handles JSON object and form-encoded bodies and leaves every other body, such as FormData, as written. If you call the endpoints another way, or send another kind of body, send the signed query yourself. Your own page parameters can sit in the same URL, but keep them out of oauth_query.
The authorize endpoint runs these steps in order and stops at the first one that needs the user:
beforeAuthorizationrefuses the request or asks for a new sign-in.- No session, a session older than
max_age, orprompt=login: redirect tologinPage.prompt=createredirects to the sign-up page instead. prompt=select_account, orselectAccount.shouldRedirectreturnstrue: redirect to the select account page.signup.shouldRedirectreturnstrueor a path: redirect to the sign-up page.postLogin.shouldRedirectreturnstrue: redirect to the post login page.prompt=consent, or the client lacksskip_consentand stored consent does not cover the requested scopes, claims, and resources: redirect toconsentPage.- Redirect to the client's
redirect_uriwith the authorization code.
With prompt=none, any step that needs the user returns an error such as login_required or consent_required to the client instead of redirecting.
Once Entro Auth has validated the request, the shouldRedirect callbacks of signup, selectAccount, and postLogin, and postLogin.consentReferenceId, receive a URLSearchParams copy of it as query. Read a parameter the client added with query.get, and a repeatable one with query.getAll, such as query.getAll("resource") for the resources a request targets.
Entro Auth also applies these rules to the authorize request (OAuth 2.1 §4.1.1):
response_typemust becode, and PKCE accepts onlyS256(RFC 7636 §4.2).stateis optional and echoed back when sent. Clients should still send it (RFC 6749 §10.12).- Every success and error response includes
iss(RFC 9207 §2). resourcerestricts the tokens to a resource server (RFC 8707 §2). See Resources.
Authorization policy
Some requests need more than a signed-in user before the provider may continue. For example, a client may ask for a stronger sign-in with acr_values, which OIDC Core treats as a preference, not a requirement. To enforce your own rules on each authorization request, set beforeAuthorization. The provider calls it after it validates the request, on the first visit and on each later visit, such as the one after sign-in:
import { oauthProvider } from "@entro314labs/entro-auth-oauth-provider";
const MFA = "urn:example:acr:mfa";
oauthProvider({
loginPage: "/sign-in",
consentPage: "/consent",
beforeAuthorization: ({ query, session }) => {
const wantsMfa = query.acr_values?.split(" ").includes(MFA);
// `twoFactorVerified` is a session field your app sets after the second factor.
if (wantsMfa && session?.session.twoFactorVerified !== true) {
return { prompt: "login" };
}
},
})The input holds the request, the client, and the session:
queryis a copy of the validated authorization request, after the provider resolves arequest_uri. It includes parameters the client added. It never holds client credentials or therequest_uri.pushedistrueonly when your server's own/oauth2/parstored the request. A request that yourrequestUriResolverreturns reportsfalseon every visit, even if your resolver reads pushed requests from your own store, and so does everyissueAuthorizationCodecall.clientis the client's registration.sessionis the user's session on this visit, ornullbefore sign-in.headersandctxbelong to the request being handled: the visit to/oauth2/authorize, or the plugin endpoint that callsissueAuthorizationCode.
The hook decides in one of three ways:
- Return nothing to continue through the steps above.
- Return
{ prompt: "login" }to send the user tologinPage, even when they are signed in. The provider treats the request as if the client had sentprompt=login. Withprompt=none, the client receiveslogin_requiredinstead. - Throw an
APIErrorwith an OAutherrorto refuse the request.
The hook runs again after the user signs in. Return { prompt: "login" } only while the session fails your rule, as in the example. Otherwise the user lands on the sign-in page again after each sign-in. Your sign-in page must also let the user meet the rule, for example by asking for the second factor.
To refuse, throw an APIError with an error and an error_description:
import { APIError } from "@entro314labs/entro-auth/api";
throw new APIError("BAD_REQUEST", {
error: "interaction_required",
error_description: "this client requires a managed device",
});The provider redirects to the validated redirect_uri with error, error_description, and iss in the query. If the client sent state, the provider echoes it. A refusal issues no code and does not consume a request the provider loaded from /oauth2/par. If you use requestUriResolver, your resolver controls whether its URI can be used again. Use an error from OIDC Core §3.1.2.6 or RFC 6749 §4.1.2.1, such as login_required, interaction_required, consent_required, or access_denied. When the user cannot meet an authentication requirement at all, unmet_authentication_requirements from OpenID Connect Unmet Authentication Requirements 1.0 tells the client so. Any other error, such as a redirect thrown with ctx.redirect, passes through unchanged.
A plugin registered as a provider extension can set beforeAuthorization too. Extension hooks run first, in registration order, and then your own. Every hook runs unless one throws. A hook that throws ends the request even when another one asked for a sign-in.
The hook also runs for codes a plugin endpoint issues with issueAuthorizationCode, with pushed: false, so a plugin cannot skip your rules. There, a thrown OAuth error fails the call with that error. { prompt: "login" } always fails it with login_required, even when the endpoint signed the user in during that request. At /oauth2/authorize, the hook runs again after sign-in and decides on the new session. A plugin endpoint runs the hook once, with the session you pass, so a { prompt: "login" } policy can never be satisfied there.
The hook does not run for device codes, CIBA requests, or other extension interaction requests, which the provider's pages also approve.
Pushed authorization requests
A plain authorization request carries its parameters in the browser URL, where the user, browser extensions, and logs can read or change them. A pushed authorization request (PAR) moves them to a direct call from the client to your server (RFC 9126). The browser then carries only a short-lived reference.
To serve the endpoint, set pushedAuthorizationRequests.enabled. The endpoint also needs the authorization_code grant, which grantTypes includes by default:
oauthProvider({
pushedAuthorizationRequests: {
enabled: true,
},
})Discovery then advertises pushed_authorization_request_endpoint. The client uses it in three steps:
- The client sends the authorization parameters to
/oauth2/paras a form-encoded POST. It authenticates as it does at the token endpoint. Aprivate_key_jwtassertion names the issuer as its audience. A public client sends onlyclient_id. - The server answers
201withrequest_uriandexpires_in. - The client sends the user to
/oauth2/authorizewith onlyclient_idandrequest_uri.
The PAR endpoint checks the parameters as the authorize endpoint would. An unregistered redirect_uri, an unknown scope, or missing PKCE for a client that requires it fails at the push with a JSON error, before the user sees a page. A pushed request that contains request_uri fails with invalid_request.
Each request_uri has these limits (RFC 9126 §4):
- The client must send the user to the authorize endpoint within
expiresInseconds,60by default. The value must be below600, the limit FAPI 2.0 sets. - It issues one authorization code. Until then, the user can reload the authorize URL. The login, consent, and other screens resume from the signed query.
- After the first visit to the authorize endpoint, it stays valid for
codeExpiresIn, the lifetime of the signed query. A sign-in that takes longer thanexpiresInstill completes. Later redirects during login and consent do not extend this deadline. - If saving the request fails on the first visit, the
request_urican be used up. The client then pushes the request again. A failure to save the authorization code leaves therequest_uriusable. - Once the code is issued, the
request_urifails withinvalid_request_uri. Continuing the same request again, such as by submitting the login form twice, sendsinvalid_request_urito the client's redirect URI. - It works only with the
client_idthat pushed it. The authorize endpoint discards it when another client presents it.
The authorize endpoint uses only the pushed parameters. It ignores any other parameter added to the authorize URL besides client_id.
Bind the code to a DPoP key
A client can send a DPoP proof with the push. Its htm must be POST, and its htu must be the full public URL of /oauth2/par. Behind a proxy, set baseURL to the public URL so the server checks the same value. The server then binds the authorization code to that key (RFC 9449 §10.1). The token request must carry a proof signed by the same key. A pushed dpop_jkt that names a different key fails with invalid_dpop_proof. See DPoP.
Require pushed requests
A required policy stops clients from starting authorization with parameters in the URL. To require PAR from every client, set required: true:
oauthProvider({
pushedAuthorizationRequests: {
enabled: true,
required: true,
},
})To require it from one client, register the client with require_pushed_authorization_requests: true (RFC 9126 §6). A client can set this on itself through dynamic registration, because it only restricts that client. The registration fails with invalid_client_metadata unless the server serves /oauth2/par or you set requestUriResolver, because the client could otherwise never start authorization.
An authorization request without request_uri then fails with invalid_request and the description pushed authorization request is required. With required: true, discovery also advertises require_pushed_authorization_requests: true. The login, consent, and other screens keep working, because they resume from the signed query.
The policy applies to /oauth2/authorize. It does not apply to codes that your own endpoint issues with issueAuthorizationCode. See Issue codes from your own endpoint.
Resolve your own request URIs
requestUriResolver resolves request_uri values that your own endpoint issues. With both PAR options set, the authorize endpoint first looks up values that /oauth2/par issued, and calls your resolver for any other value, including one that expired or already issued its code. Return null for values you did not issue. For those values, the authorize endpoint calls your resolver on each visit, including a reload. A request your resolver returns counts as pushed under a required policy.
Your resolver must enforce what the built-in endpoint does: each value expires quickly, stops working once its code is issued, and works only for the client that pushed it. To bind the code to a DPoP key from your endpoint, call verifyDpopProof there and store the proof's jkt as dpop_jkt with the request.
Issue codes from your own endpoint
A plugin endpoint can complete authorization for a signed-in user and return the authorization code itself, instead of sending the user through /oauth2/authorize. A native app that signs the user in with its own UI is one example. Call issueAuthorizationCode on the provider API with the client's request parameters and the user's session:
import { getOAuthProviderApi } from "@entro314labs/entro-auth-oauth-provider";
import { createAuthEndpoint, sessionMiddleware } from "@entro314labs/entro-auth/api";
import type { EntroAuthPlugin } from "@entro314labs/entro-auth/types";
export const codeIssuer = () =>
({
id: "code-issuer",
endpoints: {
issueCode: createAuthEndpoint(
"/app/authorize",
{ method: "POST", use: [sessionMiddleware] },
async (ctx) => {
const provider = getOAuthProviderApi(
ctx,
ctx.context.getPlugin("oauth-provider")!.options,
);
const { code } = await provider.issueAuthorizationCode({
query: ctx.body,
session: ctx.context.session,
});
return ctx.json({ authorization_code: code });
},
),
},
}) satisfies EntroAuthPlugin;The client sends this request directly, so the provider handles it as /oauth2/par handles a pushed request:
- A confidential client must send the credentials it uses at the token endpoint, in the request body or the
Authorizationheader. The provider reads them from the request your endpoint received, not fromquery. Without this check, anyone who copies the client's requests could start authorization in its name. The provider leaves the credentials out of the stored request. Aclient_idthat names another client fails withinvalid_client. - A public client, such as most native apps, is identified by its
client_idalone. It has no credentials, so itsclient_iddoes not prove which app sent the request. - A
DPoPproof on the request binds the code to its key (RFC 9449 §10). The client must then prove the same key at the token endpoint. Adpop_jktthat names a different key fails withinvalid_dpop_proof, and the proof stays usable for a corrected request. If your endpoint already calledverifyDpopProofon this request, the provider reuses that result instead of verifying the proof again, and the proof'sjtiis already used up, so a mismatch needs a new proof. - With
dpop.nonce.requiredon, a proof without a current nonce fails withuse_dpop_noncebefore client authentication. The client's retry can then reuse a one-time client assertion.
If your endpoint accepts application/x-www-form-urlencoded bodies, set cloneRequest: true in its endpoint options. Client authentication re-reads the raw form body.
Some endpoints take several requests to finish, such as a sign-in that returns a handle the client sends back on its next request. The handle already names the client, so the request that issues the code can leave out client_id. Set client_id and dpop_jkt in query from the state you stored with the handle:
const { handle, ...request } = ctx.body;
const pending = await findPendingSignIn(handle); // your own storage
if (!pending) throw new APIError("BAD_REQUEST", { error: "invalid_session" });
const { code } = await provider.issueAuthorizationCode({
query: { ...request, client_id: pending.clientId, dpop_jkt: pending.dpopJkt },
session: ctx.context.session,
});The request is then authenticated as the stored client. A client_id, Basic credentials, or a client assertion for another client fails with invalid_client, and a DPoP proof from another key fails with invalid_dpop_proof. A request without a proof still gets a code bound to the stored key, so only a token request with a proof from that key can redeem it. Reject an unknown or expired handle before the call, because without a stored client the request is authenticated as whichever client it names. Leave the handle out of query, because the provider stores the query with the code. To find your record again when the client redeems the code, pass its ID inside an object as serverContext. Earlier requests of the flow bind to the same client and key with authenticateClient's clientId and verifyDpopProof's expectedJkt.
The provider then checks the request as /oauth2/authorize does: the client, scopes, claims, resources, and PKCE. The session you pass is the account the code is for, so account selection does not run. It issues the code only when the client has skip_consent or the user already consented to everything requested. Any step that would show a page fails instead, with a 400 error:
consent_required: the user has not consented to the request.login_required: the session expired. Also returned when the request asks for a new sign-in, withprompt=loginor amax_agethe session is older than, and your endpoint did not sign the user in during this request.interaction_required: the request has apromptother thannoneorlogin, orsignup.shouldRedirectorpostLogin.shouldRedirectreturns a redirect.- The error that
beforeAuthorizationthrows, orlogin_requiredwhen it asks for a sign-in. access_denied: the session cannot meet an essentialacrthe request names.
Send the user to /oauth2/authorize if signing in, giving consent, or completing another interaction can satisfy the request. If your policy denies the request outright, return its error to the client. Request validation errors, such as invalid_client or invalid_scope, mean the request itself is invalid, as they do at /oauth2/authorize. Errors your own hooks throw, such as from consentReferenceId, pass through unchanged.
Pass the request parameters themselves. A request_uri fails with invalid_request, including one from /oauth2/par. That reference is for the browser step of /oauth2/authorize. A request object fails with request_not_supported.
A required PAR policy does not apply here, whether you set it for every client or the client registered it. The policy keeps authorization parameters out of the browser URL. Your endpoint receives them in a direct, client-authenticated request, as /oauth2/par does.
redirect_uri is optional. When the request has one, it must be registered for the client, and the result's redirectURL carries the code, state, and iss. Without one, the token request must omit redirect_uri too (RFC 6749 §4.1.3). The code expires after codeExpiresIn and redeems once at the token endpoint, like a code from /oauth2/authorize.
Your endpoint must authenticate the user before it calls issueAuthorizationCode. The method trusts the session you pass.
A client sends prompt=login or max_age=0 to require a new sign-in, even when the user is already signed in (OIDC Core §3.1.2.1). To accept these requests, your endpoint checks the user's credentials and creates the session in the same request that calls issueAuthorizationCode, for example with ctx.context.internalAdapter.createSession(user.id) and then setSessionCookie(ctx, { session, user }), imported from @entro314labs/entro-auth/cookies. Then it passes { session, user } to issueAuthorizationCode, with only the authorization request parameters as query. Without such a session, the error description is the request requires a new sign-in. The provider records each session created during a request, and accepts the request only for one of those. A session from an earlier request does not count, even when this request refreshes it. A session created inside a database transaction counts once the transaction commits. The code's auth_time is the new session's creation time.
Creating a session is what the provider treats as the new sign-in. Create one only after your endpoint has verified the user's credentials in that request.
Check the client before the user's credentials
An endpoint that checks a password or another credential should first confirm which client is asking. Otherwise, a request in another client's name, or from another DPoP key, could still learn whether the password is right. Call challengeDpopNonce, authenticateClient, and verifyDpopProof first, then check the user's credentials, then call issueAuthorizationCode on the same request. With dpop.nonce.required on, challengeDpopNonce answers a proof without a current nonce with use_dpop_nonce before client authentication uses up a one-time client assertion:
await provider.challengeDpopNonce();
const { clientId } = await provider.authenticateClient({
clientId: pending.clientId,
// A public client sends no credentials. A confidential client still must.
requireCredentials: false,
});
await provider.verifyDpopProof({ expectedJkt: pending.dpopJkt });
const user = await verifyPassword(ctx.body); // your own check, throws on failure
const session = await ctx.context.internalAdapter.createSession(user.id);
const { code } = await provider.issueAuthorizationCode({
query: { ...pending.query, client_id: clientId },
session: { session, user },
});issueAuthorizationCode reuses what those calls proved on this request, instead of checking again. A second check would reject a private_key_jwt assertion or a DPoP proof as replayed. The method still requires a match:
- A
client_idinquerymust name the client thatauthenticateClientreturned. Otherwise, the call fails withinvalid_client. - A
dpop_jktinquerymust name the key of the proof thatverifyDpopProofverified. Otherwise, the call fails withinvalid_dpop_proof. Without adpop_jkt, the code is bound to that proof's key.
Only results the provider produced on the same request count, so your code cannot pass in a client or a proof that was never checked.
Validate the request before the user signs in
An endpoint that signs the user in over several requests should check the authorization request on the first one. Otherwise, a request error such as an unknown scope appears only after the user has entered their credentials. Call validateAuthorizationRequest with the client's request parameters:
const { query, client } = await provider.validateAuthorizationRequest({
query: ctx.body,
});
// Store `query` with the handle you return, then pass it to
// issueAuthorizationCode on the last request.The method runs the request checks that /oauth2/authorize and issueAuthorizationCode run: the client, response_type, the redirect_uri when present, scopes, claims, resources, and PKCE. An invalid request fails with a 400 error carrying the code /oauth2/authorize reports for the same request, such as invalid_scope or invalid_target. The method never redirects, issues no code, stores no pushed request, and records no DPoP proof. Looking up the client and resources can still write, as it does for /oauth2/authorize: a client discovered from a client ID metadata document is saved, and onClientCreated runs for it. It needs no session.
The method does not run beforeAuthorization, because that policy looks at the session as well as the request. On a plugin endpoint the policy runs inside issueAuthorizationCode, after your endpoint has checked the user's credentials, so a refusal can arrive later than it does at /oauth2/authorize.
The request must name its client with client_id. A request_uri fails with invalid_request, and a request object fails with request_not_supported, as with issueAuthorizationCode.
The result holds two values:
query: the request after validation, with the client's default scopes filled in when the request named none. Client credentials such asclient_secretare left out. Pass it toissueAuthorizationCodeunchanged.client: the fields a sign-in page may show, such asnameandicon, plustokenEndpointAuthMethodandapplicationType. CallgetClientfor the full registration.
The result is advisory. validateAuthorizationRequest does not authenticate the client, so your endpoint must still authenticate a confidential client, for example with authenticateClient. issueAuthorizationCode checks the request again on the last request, together with the session, consent, prompt, max_age, and beforeAuthorization.
Report how the user signed in
Your endpoint knows which methods it checked, such as a password and a one-time code. Pass them as amr, using the values from RFC 8176, so the ID token's amr claim lists them. List only methods your server verified in this flow. Never copy amr values from the client's request, because the ID token asserts them to the client as the provider's own statement:
const { code } = await provider.issueAuthorizationCode({
query,
session,
amr: ["pwd", "otp"],
});When you configure authenticationContext.resolve, the resolver receives these values as amr, and its result decides the code's acr and amr. Return the amr it receives to keep them. Without a resolver, the code carries the methods you pass, and no acr beyond the default "0". This matches issueTokens and completeCibaRequest, which also record the amr you pass without calling a resolver.
The methods reach only the ID token, never the access token, so they are ignored for a request without the openid scope. The code's auth_time always comes from the session's creation time, so your endpoint cannot report an earlier sign-in than the session proves.
Carry your own state to the token request
An endpoint that keeps its own record for a flow may need that record again when the client redeems the code. For example, an endpoint that gives the client a handle can return a new handle with the tokens. Pass the values you need as serverContext:
const { code } = await provider.issueAuthorizationCode({
query: { ...request, client_id: pending.clientId, dpop_jkt: pending.dpopJkt },
session: ctx.context.session,
serverContext: { signInId: pending.id },
});The provider stores the values with the code. When the client redeems the code, customTokenResponseFields receives them as verificationValue.serverContext:
oauthProvider({
customTokenResponseFields: async ({ grantType, verificationValue }) => {
const signInId = verificationValue?.serverContext?.signInId;
if (grantType !== "authorization_code" || typeof signInId !== "string") {
return {};
}
return { handle: await renewSignInHandle(signInId) }; // your own storage
},
})Only your server sets serverContext, with the same guarantee as the serverContext on Entro Auth's OAuth state: a request cannot set it. A code from /oauth2/authorize has none, and the provider never copies the client's request parameters into it. Set it only from values your server determined, so the callback can trust what it reads. The provider keeps the values apart from the fields it stores with the code. A key such as userId or query changes nothing about the code or the tokens it issues.
The callback runs for every code a client redeems, whichever endpoint issued it. When more than one endpoint sets serverContext, nest each endpoint's values under its own key, so the callback reads only the values that endpoint stored. A plugin that other apps install should use its plugin ID as the key, as in serverContext: { "my-plugin": { signInId } }.
Your app's customTokenResponseFields is the only reader of serverContext. A plugin has no callback of its own for it, so the plugin must document its key, and the app reads that key in customTokenResponseFields and returns the fields to add.
The value must be a JSON object. The callback reads it back in its JSON form. For example, a Date inside it arrives as a string. Any other value fails with a 500 server_error, and no code is issued. The provider stores the values as plain JSON with the code. Store a reference, such as a record ID, rather than a secret or personal data. Refresh requests do not receive the values.
Login page
To send users to your sign-in page, set loginPage. When the sign-in request carries oauth_query and creates a session, the plugin continues the authorization flow. Sign-ins that return through a provider callback continue it only through /sign-in/social and, for OIDC providers, /sign-in/sso; SAML and generic OAuth sign-ins end on callbackURL. With oauthProviderClient, your page needs no OAuth code.
A sign-in can end without a session: an account with two-factor on is held to its second step, and a provider callback then lands on callbackURL with twoFactorRedirect=true. That page is your own and no longer carries the signed query, so the second step cannot send it. The plugin keeps the request for it: when a provider callback ends without a session, the request it came back with goes into a signed cookie for ten minutes, and the next request of that browser that creates a session continues the authorization and clears the cookie. A second step that follows a password or a code on the login page itself carries oauth_query as any other request of that page does.
oauthProvider({
loginPage: "/sign-in",
})Consent page
To ask users to approve a client, set consentPage. A client with skip_consent: true skips this page. A request with prompt=consent shows it anyway. Device approvals from oauthDeviceAuthorization() and CIBA (Client-Initiated Backchannel Authentication) requests always show it.
oauthProvider({
consentPage: "/consent",
})To trust the consent query, verify it on the server before you render the page. The query holds client_id, scope, and, when requested, claims. The helper below keeps only the signed parameters, so your page's own parameters do not break the signature. It reads the provider's secret from auth.$context, so run it only on the server.
import { verifyOAuthQueryParams } from "@entro314labs/entro-auth-oauth-provider";
import { auth } from "@/lib/auth";
export async function getVerifiedConsentQuery(request: Request) {
const params = new URL(request.url).searchParams;
const signed = new Set(["sig", "ba_param", ...params.getAll("ba_param")]);
const query = new URLSearchParams(
[...params].filter(([key]) => signed.has(key)),
).toString();
const { secret } = await auth.$context;
if (!(await verifyOAuthQueryParams(query, secret))) return null;
return new URLSearchParams(query);
}If the helper returns null, return an error response. The check rejects only queries that were changed or have expired. It does not prove that the client exists, that the user is signed in, or that the scopes are valid.
To show which client is asking, load it with the signed client_id. The call throws a 401 error without a session, and a 404 error for unknown or disabled clients.
const client = await auth.api.getOAuthClientPublic({
query: { client_id: query.get("client_id")! },
headers: request.headers,
});For any client an administrator did not create, whoever registered it chose its name, logo, and links. That includes dynamically registered and CIMD clients, and clients any signed-in user created with createOAuthClient while clientPrivileges is unset. Treat client_name, logo_uri, client_uri, tos_uri, and policy_uri as claims the client makes about itself (RFC 7591 §5). A client can copy the name or logo of a well-known app, so none of them proves who the client is.
On the consent page:
- Show the host of the signed
redirect_uri, so the user can see where the response goes. A native app can use a private-use scheme such ascom.example.app:/callback, which has no host, so show the whole URI for those. - When
client_idis an HTTPS URL, as it is for a CIMD client, also show its host. The user can then check that the request comes from the application they expect (CIMD draft-03 §10.6). - Show
client_nameandclient_urias text the client supplied, for example "Acme Notes says it is acme.example", and do not use them to mark a client as verified. For a CIMD client,client_urimust share theclient_idorigin only whileoriginBoundFieldsincludes it. Even then, the shared origin ties the link to theclient_idhost but does not vouch for who runs it. Show a verified mark only for clients you reviewed yourself, such as those on your own allow list. - Render
client_uri,tos_uri, andpolicy_urias links only when they start withhttps:. Otherwise show the value as plain text or omit it. - Do not put
logo_uriin an<img>tag. Entro Auth never fetches or proxies the logo, and a hotlinked image lets the client change it after review, serve it differently to the user than to you, and learn when the user opens the page. Either omit the logo or fetch it yourself, and serve it from a server you trust. The fetch uses a URL the client chose, so refuse private and internal addresses when the connection is made, do not follow redirects, and cap the response size. Check that the result is a valid image that your content security policy allows. CIMD draft-03 §10.9 requires this of a server that shows a CIMD client's logo.
Then show the requested scope and claims.userinfo names, and call oauth2.consent with the user's choice.
Device approvals and CIBA requests carry no redirect_uri. For a client an administrator did not create, the page then has no host to show beside the name the client chose. Label that name and logo as supplied by the client, not as the client's identity. Device approval and CIBA queries carry other fields to show:
- A device approval's query also carries
user_code. Show it so the user can check that it matches the code on their device. - A CIBA request's query carries the client's
binding_messagewhen the client sent one. - Both queries carry each requested
resource, the API the token is for. Show each one. See Production security requirements.
const { data, error } = await authClient.oauth2.consent({ accept, // required, Accept or deny the request. scope, // Space-separated accepted scopes, a subset of the requested ones. Defaults to all requested scopes. claims, // Accepted OIDC claims request object. Defaults to all requested claims. reference_id, // The reference the user chose, such as an organization ID. `postLogin.consentReferenceId` receives it as `consent.referenceId` and decides whether to accept it. Without that callback, accepting with it fails with `invalid_request`. A denied consent ignores it. oauth_query, // The signed query of the current page. The client plugin sends it for you.});acceptbooleanrequiredAccept or deny the request.
scopestringSpace-separated accepted scopes, a subset of the requested ones. Defaults to all requested scopes.
claimsstring | Record<string, unknown>Accepted OIDC claims request object. Defaults to all requested claims.
reference_idstringThe reference the user chose, such as an organization ID. postLogin.consentReferenceId receives it as consent.referenceId and decides whether to accept it. Without that callback, accepting with it fails with invalid_request. A denied consent ignores it.
oauth_querystringThe signed query of the current page. The client plugin sends it for you.
The response is { redirect: true, url }. By default, the auth client sends the browser to url. If you call the endpoint another way, send the browser to url yourself.
With accept: false, the user returns to the client with access_denied, and any consent given earlier stays unchanged. This redirect happens only while the client is enabled and the redirect_uri is still valid for it. If the client was disabled or deleted, or the redirect_uri no longer passes redirect URI validation, the url points to the server error page instead. Validation fails when the URI was removed from the client's registration under the default policy, or when allowInsecureRedirectUri or validateRedirectUri no longer accepts it. When the user denies a device approval, the user returns to the device verification page instead of the client. When the user denies a CIBA request, the user goes to resultPage. Both URLs carry status=denied. To remove consent, see Manage consents.
Stored consent
When the user accepts, Entro Auth stores a consent for that user, client, and consent reference. A stored consent holds the scopes, resources, and UserInfo claims that the user approved for the client and did not take back. Each acceptance updates it:
- The scopes and UserInfo claims the user accepts are added.
- The scopes and UserInfo claims the page offered and the user left out are removed.
- The resources the request names are added. The page cannot decline a resource.
- Everything else stays, including what the user approved on an earlier page that this page did not offer.
A client cannot shrink a stored consent by asking for less. For example, the user approves openid offline_access for one device, and then openid for a second device of the same client. The consent keeps both scopes. Only the user takes access back: by declining a scope or claim that the consent page offers, by narrowing the consent with updateOAuthConsent, or by deleting it. See Manage consents.
For an authorization request, the consent page shows again only when the stored consent does not cover it, or when the request sends prompt=consent. With prompt=none, a request the stored consent does not cover gets consent_required instead. A client with skip_consent skips the page unless the request sends prompt=consent. Device approvals and CIBA approvals from the link show the page every time. When two acceptances for the same client and reference arrive at the same moment, the stored consent keeps what each one added. If other writes keep changing the consent while an acceptance or updateOAuthConsent saves it, the request fails with 503 and temporarily_unavailable after five attempts. Retry it.
Sign-up account screen
To send prompt=create requests (OpenID Connect Prompt Create) to a separate sign-up page, set signup.page. Without it, Entro Auth redirects to loginPage.
oauthProvider({
signup: {
page: "/sign-up",
},
})To hold signed-in users on extra registration steps, add shouldRedirect. It receives headers, user, session, scopes, and query. Return true to redirect to page, a path to redirect there, or false to continue.
oauthProvider({
signup: {
page: "/sign-up",
shouldRedirect: async ({ user }) => {
return user.onboarded ? false : "/setup";
},
},
})When registration is done, call authClient.oauth2.continue({ created: true }). The auth client then sends the browser to the next step. See Continue endpoint.
Select account screen
To support prompt=select_account (OIDC Core §3.1.2.1), set selectAccount. shouldRedirect receives headers, user, session, scopes, and query. It returns true to redirect to page. Without selectAccount.page, that prompt returns an error. This example uses the multi-session plugin and asks whenever more than one session is signed in:
oauthProvider({
selectAccount: {
page: "/select-account",
shouldRedirect: async ({ headers }) => {
const sessions = await auth.api.listDeviceSessions({ headers });
return sessions.length > 1;
},
},
})After the user picks an account, resume the flow:
await authClient.multiSession.setActive({ sessionToken });
await authClient.oauth2.continue({ selected: true });Post-login screen
To add a step after sign-in and before consent, such as picking an organization, set postLogin with a page and these callbacks:
shouldRedirectreceivesheaders,user,session,scopes,query, andisContinuation. It returnstrueto redirect topage.consentReferenceIdreceivesuser,session,scopes,query, and, once the user accepts,consent. Until then,scopesholds the requested scopes. Once the user accepts, it holds the scopes they accepted. The callback returns the user's choice, such as an organization ID. Entro Auth stores consent separately for each reference. WhenconsentReferenceIdreturnsundefinedor an empty string, the consent given without a reference applies.
oauthProvider({
postLogin: {
page: "/select-organization",
shouldRedirect: async ({ session, headers, isContinuation }) => {
const orgs = await auth.api.listOrganizations({ headers });
if (!orgs.some((org) => org.id === session.activeOrganizationId)) {
return true;
}
return !isContinuation && orgs.length > 1;
},
consentReferenceId: ({ session }) =>
session.activeOrganizationId as string | undefined,
},
})When the user returns from your page, shouldRedirect runs again with isContinuation: true. Ask users with several organizations on a new authorization. On continuation, return false once the active organization is one the user belongs to. isContinuation does not prove a selection was made, so always check the session.
await authClient.organization.setActive({ organizationId });
await authClient.oauth2.continue({ postLogin: true });Device approvals from oauthDeviceAuthorization() and CIBA requests approved on the provider's pages run this step too. Tokens for these requests carry the referenceId that this step selects. completeCibaRequest skips this step. Tokens for requests it approves carry no referenceId.
If some scopes need a reference, throw an APIError from consentReferenceId when none is set. Entro Auth does not check this for you. For how references reach token claims, see Organizations and Consent reference claim.
Organization from the request or the consent page
A client can name the organization it needs in its authorization request, such as organization=org_123, and consentReferenceId reads it from query. Your consent page can instead let the user pick one and send it as reference_id to /oauth2/consent. consentReferenceId receives that pick as consent.referenceId. Neither value comes from your server, so check that the user belongs to the organization before returning it.
consent is set only when the user accepts. Until then, return undefined while no organization is known. The consent page can then ask.
An authorization request from a client with skip_consent gets no consent page unless it sends prompt=consent. When such a request names no organization, refuse it with invalid_request.
A request can carry a custom parameter such as organization more than once. Refuse a request whose organizations disagree.
// Clients created with `skip_consent` skip the consent page on authorization requests.
const skipConsentClientIds = new Set(["internal-dashboard"]);
oauthProvider({
scopes: ["openid", "profile", "email", "read:organization"],
postLogin: {
page: "/select-organization",
shouldRedirect: () => false, // the consent page asks instead
consentReferenceId: async ({ user, scopes, query, consent }) => {
if (!scopes.includes("read:organization")) return undefined;
// The request and the consent page must agree on one organization.
const named = new Set(
[...query.getAll("organization"), consent?.referenceId].filter(Boolean),
);
if (named.size > 1) {
throw new APIError("BAD_REQUEST", { error: "invalid_request" });
}
const [organizationId] = named;
const skipsConsent = skipConsentClientIds.has(query.get("client_id") ?? "");
// Not chosen yet: let the consent page ask.
if (!organizationId && !consent && !skipsConsent) return undefined;
// A `skip_consent` client, or a user who accepted without picking, named none.
if (!organizationId) {
throw new APIError("BAD_REQUEST", { error: "invalid_request" });
}
// `isMember` stands for your own membership lookup.
if (!(await isMember(user.id, organizationId))) {
throw new APIError("FORBIDDEN", { error: "access_denied" });
}
return organizationId;
},
},
})Your consent page must show the organization being approved: the one the request names, or the one the user picks. Send the user's pick as reference_id:
await authClient.oauth2.consent({
accept: true,
reference_id: pickedOrganizationId, // the organization the user picked
});Continue endpoint
To resume authorization from an account page, call this endpoint with the flag that matches the page. Entro Auth runs the authorize steps again and responds with { redirect: true, url }. The url can be another account page, the consent page, or the client's redirect_uri. By default, the auth client sends the browser there. Account selection does not run again: it runs only on the request to /oauth2/authorize itself.
Without a flag or the signed query, the call returns a 400 invalid_request error. Call it from the page that Entro Auth redirected to, where the URL still carries the signed query. Without oauthProviderClient, send that query as oauth_query.
const { data, error } = await authClient.oauth2.continue({ selected, // Confirms an account was selected on the select account page. created, // Confirms an account was registered on the sign-up page. postLogin, // Resumes after the post login page. `postLogin.shouldRedirect` runs again with `isContinuation: true`. oauth_query, // The signed query of the current page. The client plugin sends it for you.});selectedbooleanConfirms an account was selected on the select account page.
createdbooleanConfirms an account was registered on the sign-up page.
postLoginbooleanResumes after the post login page. postLogin.shouldRedirect runs again with isContinuation: true.
oauth_querystringThe signed query of the current page. The client plugin sends it for you.
Manage consents
To let users list and change their consents, use these endpoints. Each requires a session and only returns or changes the signed-in user's consents.
| Server method | Path | Method | Input |
|---|---|---|---|
getOAuthConsent | /oauth2/get-consent | GET | query id |
getOAuthConsents | /oauth2/get-consents | GET | none |
updateOAuthConsent | /oauth2/update-consent | POST | body { id, update: { scopes } } |
deleteOAuthConsent | /oauth2/delete-consent | POST | body { id } |
Two first acceptances at the same moment can each store a row for the same client and consent reference. These endpoints treat such rows as one consent. getOAuthConsents lists them once. getOAuthConsent and updateOAuthConsent return the oldest row with the scopes, resources, and UserInfo claims of all of them, so its id can differ from the one you sent. deleteOAuthConsent deletes all of them.
updateOAuthConsent replaces the consent's scopes with the ones you send, which must be allowed for the client. A later request for a removed scope shows the consent page again. Narrowing does not revoke tokens already issued: they keep their scopes until they expire or are revoked. To revoke the tokens issued under a consent, delete it.
Deleting a consent revokes the refresh tokens and opaque access tokens issued under it. JWT access tokens stay valid until they expire, unless revocableJwtAccessTokens revokes them. Tokens the user holds for the same client under another consent reference stay valid. See Revoke tokens with a consent.
After the user deletes a consent, the client's next authorization request under that consent reference shows the consent page again. With prompt=none, it gets consent_required instead. A client with skip_consent is not asked, so it can still get new tokens. To stop such a client, disable or delete it.
A pending authorization code follows the consent. So do an approved device code and a CIBA request the user approved from the link. Redeeming one needs a stored consent for its user, client, and consent reference that still covers its scopes and resources. For an authorization code, the consent must also cover its UserInfo claims. Once the user deletes the consent, or narrows it below what was approved, redeeming it fails with invalid_grant. A later approval for the same client and consent reference adds to the consent, so it leaves the code valid. If the user declines one of the code's scopes or claims on that later consent page, the consent no longer covers the code, and redeeming it fails the same way.
If the user deletes the consent and then approves the same access again for the same client and consent reference, the code is valid again. Redemption bypasses this check while the client is configured with skip_consent, even if a stored consent exists. A redemption that passed this check just before the consent was deleted can still finish, and the tokens it issues stay valid. A CIBA request approved with completeCibaRequest stores no consent, so it is not checked.
const { error } = await authClient.oauth2.updateConsent({
id: consentId,
update: { scopes: ["openid", "profile"] },
});
if (error) {
// A scope the client is not allowed to use returns a 400 invalid_request error.
}