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_url is your app's identity. localhost callbacks 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

StepMethod and URLWho calls it
Consent pageGET https://portal.<domain>/authorize?…The user's browser (your app redirects or links to it)
Code exchangePOST https://portal.<domain>/api/portal/v1/oauth/exchangeYour app's backend (or your CLI)
Inference with the keyhttps://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 from A–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 };
}

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>
ParameterRequiredDescription
callback_urlYesWhere the browser is sent back with the code. See Callback URL rules.
code_challengeYesBASE64URL(SHA256(code_verifier)) from step 1.
code_challenge_methodYesMust be S256. plain and requests without a challenge are refused.
stateYesYour random CSRF value (1–512 characters). It comes back unchanged on the callback — on success and on deny.
key_labelNoThe 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_idNoPreselects 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:

  1. If state does not match the value you stored, stop — the request did not come from a flow you started.
  2. If error=access_denied, the user declined; show a message and let them retry.
  3. If error is present and is not access_denied (server_error, temporarily_unavailable), the authorization failed; show the error_description and let the user retry the connect flow.
  4. Otherwise, take code and 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"
}
FieldDescription
keyThe API key. It is returned only here, once — store it securely.
nameThe 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_prefixThe non-secret prefix the user sees in the portal's key list.
project_idThe project the user chose.
created_viaAlways 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 storage

Exchange 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.

Statuserror.codeWhenWhat to do
400invalid_grantThe 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.
400invalid_request (param: "code_challenge_method")code_challenge_method is missing or not S256.Send "S256".
400invalid_requestThe body is not valid JSON.Fix the request.
429rate_limitedToo 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

CallbackAccepted
https:// on any host, any path, with or without a query stringYes
http://localhost:<port>/…, http://127.0.0.1:<port>/…, http://[::1]:<port>/… — any portYes (for local tools and CLIs)
http:// on any other hostNo
Any other scheme (custom schemes, ftp:, …)No
A URL with a #fragmentNo
A URL with credentials (https://user@host/…), a backslash, whitespace or control charactersNo
A non-ASCII (internationalized) hostNo — send the punycode form (xn--…)
Longer than 2048 charactersNo

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 state for every attempt, and keep the verifier secret — never send it to the browser in a URL, never log it.
  • Always check state on 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

OpenRouterTokenFactory
Consent URLhttps://openrouter.ai/authhttps://portal.<domain>/authorize
Exchange URLPOST https://openrouter.ai/api/v1/auth/keysPOST https://portal.<domain>/api/portal/v1/oauth/exchange (portal host, not the API host)
code_challenge_methodS256 or plain; PKCE optionalS256 only, required
stateOptional; not returned on denyRequired; returned on success and on deny
DenyRedirect without state?error=access_denied&state=…
Headless mode (no callback_url)SupportedNot yet — callback_url is required
key_labelUp to 100 characters; default: app nameSame — 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 errors400 bad method, 403 bad code/verifier, 403 expired, 405 not POST400 invalid_grant for every code/verifier failure, 400 invalid_request for a bad method, 429 rate_limited
Scope of the keyAccount-wide (optionally a workspace)One project, chosen by the user (project_id preselects)
Spend limit / expiry on the consent pageSupportedNot 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".

We use strictly necessary cookies to record your choice and run this site. We do not use cookies for advertising or tracking. See the Cookie Policy.