Connect TokenFactory (OAuth PKCE)
Let users connect your app to TokenFactory in one click — your app receives a project API key for them through an OAuth 2.0 Authorization Code + PKCE (S256) flow, with no client registration.
Connect TokenFactory lets a third-party app — a web app, an IDE extension,
a CLI agent — get a TokenFactory API key for a user without asking them to copy
one out of the portal. The user signs in to TokenFactory, sees which app is
asking, picks the project the key is for and clicks Authorize; your app
receives an ordinary project API key it can use against
https://api.<domain>/v1.
The flow is OAuth 2.0 Authorization Code with PKCE (RFC 7636) and has the same shape and parameter names as OpenRouter's OAuth PKCE flow, so an existing "Connect OpenRouter" client needs only a few changes — see Differences from OpenRouter.
- No client registration and no client secret. Your
callback_urlis your app's identity.localhostcallbacks on any port work for local tools. - The key is a normal project API key. The user sees it with the project's other API keys and can revoke it there at any time. Usage is attributed to it like any other key.
- Codes are single-use and expire after 10 minutes, are stored hashed, and
are bound to your app by PKCE — an intercepted code is useless without your
code_verifier.
Note
Connect TokenFactory is enabled per deployment. If the exchange endpoint answers
404, it is not enabled on the TokenFactory deployment you are targeting.
Endpoints
| Step | Method and URL | Who calls it |
|---|---|---|
| Consent page | GET https://portal.<domain>/authorize?… | The user's browser (your app redirects or links to it) |
| Code exchange | POST https://portal.<domain>/api/portal/v1/oauth/exchange | Your app's backend (or your CLI) |
| Inference with the key | https://api.<domain>/v1/* | Your app, with Authorization: Bearer <key> |
<domain> is the TokenFactory deployment's domain. Both OAuth URLs are on the
portal host; only inference uses the API host.
Step 1: Create a code verifier and an S256 challenge
For every connect attempt, generate:
- a
code_verifier: a cryptographically random string of 43–128 characters fromA–Z a–z 0–9 - . _ ~(32 random bytes, base64url-encoded without padding, gives 43 characters); - a
code_challenge:BASE64URL(SHA256(code_verifier)), without padding; - a
state: a random, unguessable value (1–512 characters) your app will check when the user comes back.
Keep the verifier and state on your side (server session, or in memory for a
CLI). Never put the verifier in the URL.
function base64url(bytes: Uint8Array): string {
let s = '';
for (const b of bytes) s += String.fromCharCode(b);
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
export async function createPkce() {
const codeVerifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(codeVerifier));
const codeChallenge = base64url(new Uint8Array(digest));
const state = base64url(crypto.getRandomValues(new Uint8Array(16)));
return { codeVerifier, codeChallenge, state };
}Step 2: Send the user to the TokenFactory consent page
Redirect (or link) the user's browser to:
https://portal.<domain>/authorize
?callback_url=<your callback URL, URL-encoded>
&code_challenge=<code_challenge>
&code_challenge_method=S256
&state=<state>
&key_label=<optional key name>| Parameter | Required | Description |
|---|---|---|
callback_url | Yes | Where the browser is sent back with the code. See Callback URL rules. |
code_challenge | Yes | BASE64URL(SHA256(code_verifier)) from step 1. |
code_challenge_method | Yes | Must be S256. plain and requests without a challenge are refused. |
state | Yes | Your random CSRF value (1–512 characters). It comes back unchanged on the callback — on success and on deny. |
key_label | No | The label for the key that will be created, at most 100 characters. The key is named OAuth: <label> — for example OAuth: My App. The user sees the full name on the consent page and can edit the label. If you leave it out, the label is your app's callback host (for example OAuth: myapp.example.com, or OAuth: localhost:51423 for a local callback). |
project_id | No | Preselects a project in the consent page's project picker. The user can still choose another project they belong to. |
const { codeVerifier, codeChallenge, state } = await createPkce();
// Store codeVerifier + state in the user's server-side session (or sessionStorage).
session.set('tf_pkce', { codeVerifier, state });
const url = new URL('https://portal.<domain>/authorize');
url.searchParams.set('callback_url', 'https://myapp.example.com/tokenfactory/callback');
url.searchParams.set('code_challenge', codeChallenge);
url.searchParams.set('code_challenge_method', 'S256');
url.searchParams.set('state', state);
url.searchParams.set('key_label', 'My App');
window.location.assign(url.toString()); // or: res.redirect(url.toString())Step 3: The user signs in and approves (or denies)
On the consent page the user — signing in first if they have no portal session, and coming straight back afterwards — sees:
- which app is asking (your callback host) and that it will be able to create an API key, use the organization's credits and make requests on their behalf;
- your full
callback_url, with a prompt to make sure they recognise it; - a project picker and the editable key name, with the exact name the
key will get (
OAuth: <label>) (a member can only authorize a key in a project they belong to — the same rule as creating a key in the portal); - Deny and Authorize.
Authorize sends the browser to your callback with a code and your state:
https://myapp.example.com/tokenfactory/callback?code=<authorization code>&state=<state>Deny sends the browser to your callback with an OAuth error and your state, and no code is issued:
https://myapp.example.com/tokenfactory/callback?error=access_denied&state=<state>If Authorize itself fails — the deployment has the feature off, the portal is momentarily unavailable, or the session could not be used — the browser is also sent back to your callback with an error and your state (RFC 6749 §4.1.2.1), instead of being left on the portal:
https://myapp.example.com/tokenfactory/callback?error=server_error&error_description=…&state=<state>error is temporarily_unavailable for a 503 (safe to retry shortly) and
server_error for any other failure. An error is only ever sent to a
callback_url that passed the Callback URL rules; if
the callback is invalid the consent page refuses the request up front and never
navigates.
If your callback_url already has a query string, it is kept and code/state
(or error/state) are added to it.
In your callback handler:
- If
statedoes not match the value you stored, stop — the request did not come from a flow you started. - If
error=access_denied, the user declined; show a message and let them retry. - If
erroris present and is notaccess_denied(server_error,temporarily_unavailable), the authorization failed; show theerror_descriptionand let the user retry the connect flow. - Otherwise, take
codeand exchange it within 10 minutes (step 4).
Step 4: Exchange the code for an API key
POST https://portal.<domain>/api/portal/v1/oauth/exchange with a JSON body.
The request is not authenticated — the single-use code plus your verifier are
the credential — so make it from your backend (or CLI), over HTTPS.
Request
{
"code": "<code from the callback>",
"code_verifier": "<code_verifier from step 1>",
"code_challenge_method": "S256"
}Response — 201 Created
{
"key": "tf-…",
"name": "OAuth: My App",
"key_prefix": "tf-…",
"project_id": "6f1c…",
"created_via": "oauth_pkce"
}| Field | Description |
|---|---|
key | The API key. It is returned only here, once — store it securely. |
name | The key's name: OAuth: followed by your key_label, the user's edit of it, or your app name. This is the name the user sees in the portal's key list. |
key_prefix | The non-secret prefix the user sees in the portal's key list. |
project_id | The project the user chose. |
created_via | Always oauth_pkce. |
// e.g. an Express/Next.js route handler for /tokenfactory/callback
const params = new URL(req.url, 'https://myapp.example.com').searchParams;
const saved = session.get('tf_pkce');
if (!saved || params.get('state') !== saved.state) throw new Error('state mismatch');
if (params.get('error') === 'access_denied') return showDenied();
const res = await fetch('https://portal.<domain>/api/portal/v1/oauth/exchange', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
code: params.get('code'),
code_verifier: saved.codeVerifier,
code_challenge_method: 'S256',
}),
});
if (!res.ok) {
const { error } = await res.json();
throw new Error(`exchange failed: ${res.status} ${error.code}`); // restart the flow
}
const { key } = await res.json();
session.delete('tf_pkce');
await saveKeyForUser(key); // your secure storageExchange errors
Errors use the standard TokenFactory error envelope (error.type, error.code,
error.message, error.param, error.request_id; see Errors).
Branch on the status and error.code, never on message.
| Status | error.code | When | What to do |
|---|---|---|---|
400 | invalid_grant | The code is unknown, expired (older than 10 minutes), already used, or the code_verifier does not match the challenge — or the user who approved it has since lost access to the project or organization. All of these answer the same way on purpose. A code is used up by the first exchange attempt, even one with a wrong verifier. | Restart the flow from step 1. |
400 | invalid_request (param: "code_challenge_method") | code_challenge_method is missing or not S256. | Send "S256". |
400 | invalid_request | The body is not valid JSON. | Fix the request. |
429 | rate_limited | Too many exchange attempts from your IP address (a short burst, then about 10 per minute), or the deployment-wide exchange ceiling was reached. Comes with Retry-After. | Wait for Retry-After seconds. |
404 | — | Connect TokenFactory is not enabled on this deployment (or the method is not POST). | Check the domain and method. |
{
"error": {
"type": "invalid_request_error",
"code": "invalid_grant",
"message": "Invalid or expired authorization code, or code_verifier does not match the challenge",
"param": null,
"request_id": "…"
}
}Step 5: Use the key
The key works like any project API key on the inference API — see Authentication and the Quickstart:
import OpenAI from 'openai';
const client = new OpenAI({ baseURL: 'https://api.<domain>/v1', apiKey: key });
const reply = await client.chat.completions.create({
model: '<provider>/<model>',
messages: [{ role: 'user', content: 'Hello!' }],
});The key carries the project's policy (model allowlist, rate limits, spend caps,
plan). If the user revokes it in the portal, requests fail with
401 inactive_api_key (or invalid_api_key); send the user through the
connect flow again.
Callback URL rules
| Callback | Accepted |
|---|---|
https:// on any host, any path, with or without a query string | Yes |
http://localhost:<port>/…, http://127.0.0.1:<port>/…, http://[::1]:<port>/… — any port | Yes (for local tools and CLIs) |
http:// on any other host | No |
Any other scheme (custom schemes, ftp:, …) | No |
A URL with a #fragment | No |
A URL with credentials (https://user@host/…), a backslash, whitespace or control characters | No |
| A non-ASCII (internationalized) host | No — send the punycode form (xn--…) |
| Longer than 2048 characters | No |
For a CLI, listen on a random local port, use
http://127.0.0.1:<port>/callback as the callback, open the consent URL in the
user's browser, and shut the listener down after the first callback. Local
callbacks are named after host:port on the consent page and as the default
key name.
There is no headless (copy-the-code) mode yet: callback_url is required.
Security notes
- Use a fresh verifier and
statefor every attempt, and keep the verifier secret — never send it to the browser in a URL, never log it. - Always check
stateon the callback before exchanging the code. - Exchange on the server. The exchange response contains the key; treat it like a password. Store it encrypted or in a secret store, never in client-side code or logs.
- Codes are single-use and short-lived. A code expires after 10 minutes, and the first exchange attempt uses it up — a failed attempt cannot be retried. Restart the flow instead.
- Users trust your callback URL. It is the identity TokenFactory shows on the consent page; use a stable HTTPS URL on a domain users recognise. Local callbacks are for development and CLIs.
- Ask for a recognisable
key_label, so the user can find and revoke your app's key later.
Differences from OpenRouter
| OpenRouter | TokenFactory | |
|---|---|---|
| Consent URL | https://openrouter.ai/auth | https://portal.<domain>/authorize |
| Exchange URL | POST https://openrouter.ai/api/v1/auth/keys | POST https://portal.<domain>/api/portal/v1/oauth/exchange (portal host, not the API host) |
code_challenge_method | S256 or plain; PKCE optional | S256 only, required |
state | Optional; not returned on deny | Required; returned on success and on deny |
| Deny | Redirect without state | ?error=access_denied&state=… |
Headless mode (no callback_url) | Supported | Not yet — callback_url is required |
key_label | Up to 100 characters; default: app name | Same — default: the callback host (TokenFactory has no app registration); the key is named OAuth: <label> |
| Exchange response | {"key": …} | {"key", "name", "key_prefix", "project_id", "created_via"} — key is the same field |
| Exchange errors | 400 bad method, 403 bad code/verifier, 403 expired, 405 not POST | 400 invalid_grant for every code/verifier failure, 400 invalid_request for a bad method, 429 rate_limited |
| Scope of the key | Account-wide (optionally a workspace) | One project, chosen by the user (project_id preselects) |
| Spend limit / expiry on the consent page | Supported | Not yet — the project's and organization's limits apply to the key |
To port a "Connect OpenRouter" client: change both URLs, always send
code_challenge_method=S256 and a state, check state on deny as well, and
treat any 400 from the exchange as "restart the flow".
Related
- Authentication — headers and key policy
- Errors — the error envelope
- Rate Limits