---
title: "Build an OAuth app"
summary: "A working app that connects to a person's Taskloader account: discovery, registration, PKCE, the callback, tokens, refresh and revocation."
updated: "2026-11-19"
url: "https://taskloader.com/docs/guides/build-an-oauth-app"
---

> Documentation index: https://taskloader.com/llms.txt

# Build an OAuth app

A working app that connects to a person's Taskloader account: discovery, registration, PKCE, the callback, tokens, refresh and revocation.

This guide builds a small command-line app that connects to someone's Taskloader account with OAuth, lists their projects, and keeps working with refresh tokens. The same steps apply to web and mobile apps. The reference for every rule is [OAuth for apps](https://taskloader.com/docs/authentication/oauth.md).

The flow, in short:

1. **Discover** the authorization server from the API's metadata.
2. **Identify your app**: a client metadata document, or a one-time registration.
3. **Send the person to Taskloader** with a PKCE challenge and `resource=https://taskloader.com/api/v1`.
4. **Receive the redirect**, check `state` and `iss`, and exchange the code for tokens.
5. **Call the API**, refresh before the access token expires, and revoke when the person disconnects.

## 1. Discover

Start from the resource you want to call. Its metadata names the authorization server, whose own metadata lists the endpoints:

```bash
curl https://taskloader.com/.well-known/oauth-protected-resource/api/v1 | jq .authorization_servers
# ["https://taskloader.com/api/auth"]

curl https://taskloader.com/.well-known/oauth-authorization-server/api/auth | jq '{authorization_endpoint, token_endpoint, registration_endpoint, revocation_endpoint}'
```

The issuer has a path (`/api/auth`), so its metadata lives at `/.well-known/oauth-authorization-server/api/auth` (RFC 8414 puts the path after the well-known part). Check that the document's `issuer` equals the issuer you started from.

## 2. Identify your app

**A web app** should publish a [client metadata document](https://taskloader.com/docs/authentication/oauth.md#client-id-metadata-documents) at an HTTPS address it controls, and use that address as its `client_id`. There is no registration step, and people see your verified host on the consent screen.

```json
{
  "client_id": "https://sync.example.com/oauth/client-metadata.json",
  "client_name": "Northwind Sync",
  "redirect_uris": ["https://sync.example.com/oauth/callback"],
  "grant_types": ["authorization_code", "refresh_token"],
  "response_types": ["code"],
  "token_endpoint_auth_method": "none"
}
```

**A desktop or command-line app**, which has no website to host a document, registers itself once with [dynamic client registration](https://taskloader.com/docs/authentication/oauth.md#dynamic-client-registration) and stores the `client_id`. It uses a loopback redirect: `http://127.0.0.1/callback` matches every port, so the app can listen on whichever port is free. The example below does this.

## 3 to 5. The whole app

The program discovers the endpoints, registers once, opens a local listener for the redirect, prints the address to open, and on return exchanges the code, calls `GET /me` and `GET /projects`, and stores the tokens in `.taskloader-oauth.json` (readable only by you). Run it again later and it refreshes instead of asking again. If the connection is gone (the person disconnected the app, reset their password, or did not use it for 30 days), it asks them to connect again.

```js
// connect.mjs: node connect.mjs   (Node.js 20 or later, no packages)
import { createHash, randomBytes } from 'node:crypto';
import { readFile, writeFile } from 'node:fs/promises';
import { createServer } from 'node:http';

const RESOURCE = 'https://taskloader.com/api/v1';
const SCOPES = 'projects:read tasks:read offline_access';
const STORE = '.taskloader-oauth.json';

let store = {};
try {
  store = JSON.parse(await readFile(STORE, 'utf8'));
} catch {}
const save = () => writeFile(STORE, JSON.stringify(store), { mode: 0o600 });

// 1. Discover: resource metadata → issuer → authorization server metadata.
const resource = await (
  await fetch('https://taskloader.com/.well-known/oauth-protected-resource/api/v1')
).json();
const issuer = resource.authorization_servers[0];
const { origin, pathname } = new URL(issuer);
const server = await (
  await fetch(`${origin}/.well-known/oauth-authorization-server${pathname}`)
).json();
if (server.issuer !== issuer)
  throw new Error('The authorization server metadata does not match its issuer.');

/** Calls the token endpoint and stores the tokens it returns. */
async function token(params) {
  const response = await fetch(server.token_endpoint, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({ client_id: store.clientId, resource: RESOURCE, ...params }),
  });
  const body = await response.json();
  if (!response.ok) {
    // The connection is gone (disconnected, password reset, 30 days unused), or the
    // registration was deleted: start over with the person instead of failing every run.
    if (
      params.grant_type === 'refresh_token' &&
      ['invalid_grant', 'invalid_client'].includes(body.error)
    ) {
      if (body.error === 'invalid_client') delete store.clientId;
      delete store.accessToken;
      delete store.refreshToken;
      await save();
      return connect();
    }
    throw new Error(`${body.error}: ${body.error_description ?? ''}`);
  }
  store.accessToken = body.access_token;
  store.refreshToken = body.refresh_token ?? store.refreshToken; // Every refresh returns a new one.
  store.expiresAt = Date.now() + body.expires_in * 1000;
  await save();
}

/** Signs the person in through their browser and stores the tokens. */
async function connect() {
  const listener = createServer();
  await new Promise((resolve) => listener.listen(0, '127.0.0.1', resolve));
  const redirectUri = `http://127.0.0.1:${listener.address().port}/callback`;

  // 2. Register once: a public client with a loopback redirect (any port matches).
  if (!store.clientId) {
    const response = await fetch(server.registration_endpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        client_name: 'Northwind Sync',
        application_type: 'native',
        redirect_uris: ['http://127.0.0.1/callback'],
        grant_types: ['authorization_code', 'refresh_token'],
        response_types: ['code'],
        token_endpoint_auth_method: 'none',
      }),
    });
    const client = await response.json();
    if (!response.ok)
      throw new Error(`Registration failed: ${client.error_description ?? client.error}`);
    store.clientId = client.client_id;
    await save();
  }

  // 3. Send the person to Taskloader, with PKCE and the REST API as the resource.
  const verifier = randomBytes(48).toString('base64url');
  const state = randomBytes(16).toString('base64url');
  const authorize = new URL(server.authorization_endpoint);
  authorize.search = new URLSearchParams({
    response_type: 'code',
    client_id: store.clientId,
    redirect_uri: redirectUri,
    scope: SCOPES,
    state,
    code_challenge: createHash('sha256').update(verifier).digest('base64url'),
    code_challenge_method: 'S256',
    resource: RESOURCE,
  }).toString();
  console.log(`Open this address to connect Taskloader:\n\n${authorize}\n`);

  // 4. Receive the redirect; check state and iss before using the code.
  const params = await new Promise((resolve) => {
    listener.on('request', (request, response) => {
      const url = new URL(request.url, redirectUri);
      if (url.pathname !== '/callback') return response.writeHead(404).end();
      response.writeHead(200, { 'Content-Type': 'text/plain' }).end('You can close this tab.');
      listener.close();
      resolve(url.searchParams);
    });
  });
  if (params.get('state') !== state || params.get('iss') !== issuer)
    throw new Error('This answer does not belong to this sign-in.');
  if (params.get('error')) throw new Error(`Not connected: ${params.get('error')}`);
  await token({
    grant_type: 'authorization_code',
    code: params.get('code'),
    redirect_uri: redirectUri,
    code_verifier: verifier,
  });
}

/** Gets a new access token with the refresh token, or connects again without one. */
async function refresh() {
  if (!store.refreshToken) return connect();
  await token({ grant_type: 'refresh_token', refresh_token: store.refreshToken });
}

/** 5. Calls the API, refreshing the access token a minute before it expires. */
async function api(path, retry = true) {
  if (Date.now() > store.expiresAt - 60_000) await refresh();
  const response = await fetch(`${RESOURCE}${path}`, {
    headers: { Authorization: `Bearer ${store.accessToken}` },
  });
  const body = await response.json();
  // A 401 means the access token was revoked or expired early: refresh once, which
  // connects again if the whole connection is gone.
  if (response.status === 401 && retry) {
    await refresh();
    return api(path, false);
  }
  if (!response.ok) throw new Error(`${body.code}: ${body.detail}`);
  return body;
}

if (!store.refreshToken) await connect();
let me = await api('/me');
// The person can untick "See projects" on the consent screen. Ask again instead of
// failing on every run: approving again adds it to this connection.
if (!me.credential.scopes.includes('projects:read')) {
  console.log(
    'Taskloader did not allow this app to see your projects. Connect again and allow "See projects".',
  );
  await connect();
  me = await api('/me');
}
console.log(`Connected as ${me.user.email}. Granted: ${me.credential.scopes.join(', ')}`);
if (me.credential.scopes.includes('projects:read'))
  for (const project of (await api('/projects')).data) console.log(project.ref);
else console.log('Not listing projects: "See projects" was not allowed.');
```

```python
# connect.py: python3 connect.py   (needs requests)
import base64
import hashlib
import json
import os
import secrets
import time
import urllib.parse
from http.server import BaseHTTPRequestHandler, HTTPServer

import requests

RESOURCE = "https://taskloader.com/api/v1"
SCOPES = "projects:read tasks:read offline_access"
STORE = ".taskloader-oauth.json"

store = {}
if os.path.exists(STORE):
    with open(STORE) as file:
        store = json.load(file)


def save():
    with open(os.open(STORE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as file:
        json.dump(store, file)


# 1. Discover: resource metadata → issuer → authorization server metadata.
resource = requests.get("https://taskloader.com/.well-known/oauth-protected-resource/api/v1", timeout=30).json()
issuer = resource["authorization_servers"][0]
parts = urllib.parse.urlsplit(issuer)
server = requests.get(f"{parts.scheme}://{parts.netloc}/.well-known/oauth-authorization-server{parts.path}", timeout=30).json()
if server["issuer"] != issuer:
    raise SystemExit("The authorization server metadata does not match its issuer.")


def token(**params):
    """Calls the token endpoint and stores the tokens it returns."""
    response = requests.post(
        server["token_endpoint"],
        data={"client_id": store["client_id"], "resource": RESOURCE, **params},
        timeout=30,
    )
    body = response.json()
    if not response.ok:
        # The connection is gone (disconnected, password reset, 30 days unused), or the
        # registration was deleted: start over with the person instead of failing every run.
        if params.get("grant_type") == "refresh_token" and body.get("error") in ("invalid_grant", "invalid_client"):
            if body["error"] == "invalid_client":
                store.pop("client_id", None)
            store.pop("access_token", None)
            store.pop("refresh_token", None)
            save()
            connect()
            return
        raise SystemExit(f"{body.get('error')}: {body.get('error_description', '')}")
    store["access_token"] = body["access_token"]
    store["refresh_token"] = body.get("refresh_token", store.get("refresh_token"))  # Every refresh returns a new one.
    store["expires_at"] = time.time() + body["expires_in"]
    save()


def connect():
    """Signs the person in through their browser and stores the tokens."""
    answer = {}

    class Callback(BaseHTTPRequestHandler):
        def do_GET(self):
            url = urllib.parse.urlsplit(self.path)
            if url.path != "/callback":
                self.send_error(404)
                return
            answer.update({key: values[0] for key, values in urllib.parse.parse_qs(url.query).items()})
            self.send_response(200)
            self.send_header("Content-Type", "text/plain")
            self.end_headers()
            self.wfile.write(b"You can close this tab.")

        def log_message(self, *args):
            pass  # The query string holds the code: keep it out of logs.

    listener = HTTPServer(("127.0.0.1", 0), Callback)
    redirect_uri = f"http://127.0.0.1:{listener.server_port}/callback"

    # 2. Register once: a public client with a loopback redirect (any port matches).
    if "client_id" not in store:
        response = requests.post(
            server["registration_endpoint"],
            json={
                "client_name": "Northwind Sync",
                "application_type": "native",
                "redirect_uris": ["http://127.0.0.1/callback"],
                "grant_types": ["authorization_code", "refresh_token"],
                "response_types": ["code"],
                "token_endpoint_auth_method": "none",
            },
            timeout=30,
        )
        client = response.json()
        if not response.ok:
            raise SystemExit(f"Registration failed: {client.get('error_description') or client.get('error')}")
        store["client_id"] = client["client_id"]
        save()

    # 3. Send the person to Taskloader, with PKCE and the REST API as the resource.
    verifier = secrets.token_urlsafe(48)
    state = secrets.token_urlsafe(16)
    challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
    query = urllib.parse.urlencode(
        {
            "response_type": "code",
            "client_id": store["client_id"],
            "redirect_uri": redirect_uri,
            "scope": SCOPES,
            "state": state,
            "code_challenge": challenge,
            "code_challenge_method": "S256",
            "resource": RESOURCE,
        },
        quote_via=urllib.parse.quote,
    )
    print(f"Open this address to connect Taskloader:\n\n{server['authorization_endpoint']}?{query}\n")

    # 4. Receive the redirect; check state and iss before using the code.
    while not answer:
        listener.handle_request()
    listener.server_close()
    if answer.get("state") != state or answer.get("iss") != issuer:
        raise SystemExit("This answer does not belong to this sign-in.")
    if "error" in answer:
        raise SystemExit(f"Not connected: {answer['error']}")
    token(grant_type="authorization_code", code=answer["code"], redirect_uri=redirect_uri, code_verifier=verifier)


def refresh():
    """Gets a new access token with the refresh token, or connects again without one."""
    if "refresh_token" not in store:
        connect()
    else:
        token(grant_type="refresh_token", refresh_token=store["refresh_token"])


def api(path, retry=True):
    """5. Calls the API, refreshing the access token a minute before it expires."""
    if time.time() > store["expires_at"] - 60:
        refresh()
    response = requests.get(RESOURCE + path, headers={"Authorization": f"Bearer {store['access_token']}"}, timeout=30)
    body = response.json()
    # A 401 means the access token was revoked or expired early: refresh once, which
    # connects again if the whole connection is gone.
    if response.status_code == 401 and retry:
        refresh()
        return api(path, retry=False)
    if not response.ok:
        raise SystemExit(f"{body['code']}: {body['detail']}")
    return body


if "refresh_token" not in store:
    connect()
me = api("/me")
# The person can untick "See projects" on the consent screen. Ask again instead of
# failing on every run: approving again adds it to this connection.
if "projects:read" not in me["credential"]["scopes"]:
    print('Taskloader did not allow this app to see your projects. Connect again and allow "See projects".')
    connect()
    me = api("/me")
print(f"Connected as {me['user']['email']}. Granted: {', '.join(me['credential']['scopes'])}")
if "projects:read" in me["credential"]["scopes"]:
    for project in api("/projects")["data"]:
        print(project["ref"])
else:
    print('Not listing projects: "See projects" was not allowed.')
```

When the person opens the address, Taskloader asks them to sign in if needed, then shows the consent screen: the app's name with an **Unverified app** badge (it registered itself), "This app runs on your computer", the access it asks for, and which projects it may use. After **Allow**, the browser returns to the app, which prints:

```text
Connected as maya@northwind.example. Granted: projects:read, tasks:read
northwind/website-launch
```

## What the example gets right

- **`resource=https://taskloader.com/api/v1`** on the authorization and token requests. Without it, Taskloader issues a token for the MCP server, which the REST API refuses (`401`, `reason: "wrong_audience"`).
- **`state` and `iss` are checked** before the code is used, so a stray or forged redirect cannot slip in a code.
- **PKCE** with a fresh verifier for every sign-in.
- **The code is exchanged at once.** Codes last 60 seconds and work once.
- **Each refresh stores the new refresh token** before anything else. Refresh tokens rotate, and an old one used later revokes the connection.
- **A lost connection leads back to sign-in.** A refresh that answers `invalid_grant`, or a `401` that a refresh does not cure, starts `connect()` again instead of failing on every run.
- **Granted scopes come from `GET /me`**, because the person can untick some on the consent screen. Without **See projects** the example asks once more on each run (approving again adds the scope, with no need to disconnect first) and, if it is still not allowed, skips the listing instead of failing with `403 insufficient_scope` every time.
- **Tokens are stored readable only by the user**, and never printed or logged. The local listener does not log requests, whose addresses carry the code.
- **The registration is reused.** Registering on every run would hit the registration limit.

## When things go wrong

| Symptom                                                               | Cause                                                                                                                                                                                                                    | Fix                                                                                                                                                                                                                             |
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Taskloader shows an error page instead of the consent screen          | Unknown `client_id`, an unregistered `redirect_uri`, an unknown `resource`, or a missing or malformed PKCE challenge (`invalid_code_challenge`: the challenge is the base64url SHA-256 of the verifier, without padding) | Check the authorization address. A registration is deleted once it is a day old and nobody has it approved, which includes after **Disconnect** or a password reset: remove `.taskloader-oauth.json` and register again.        |
| Taskloader says it couldn't verify the app                            | An app with a metadata document: the document broke a rule, which the page's `reason` names (`not_json`, for example, when it is not served as `application/json`)                                                       | Fix what the page says; the rules are in [Client ID metadata documents](https://taskloader.com/docs/authentication/oauth.md#client-id-metadata-documents).                                                                                               |
| The callback has `error=access_denied`                                | The person chose **Cancel**, or must confirm their email address first                                                                                                                                                   | Let them try again when ready.                                                                                                                                                                                                  |
| The token endpoint answers `invalid_grant`                            | The code expired or was used (a refused exchange uses it up too), or a refresh token was revoked, reused or expired                                                                                                      | For a refresh, the example connects again by itself (`connect()`). For a code, start the sign-in again.                                                                                                                         |
| The token endpoint answers `invalid_request` or `invalid_target`      | A parameter is missing, or `resource` names one the authorization did not ask for                                                                                                                                        | Fix the request, then start the sign-in again: a refused exchange uses up the code, unless a parameter was repeated or `client_id` or `code` was missing.                                                                       |
| The token endpoint answers `415`                                      | The body was not form-encoded                                                                                                                                                                                            | Send `application/x-www-form-urlencoded`.                                                                                                                                                                                       |
| The token endpoint answers `429 temporarily_unavailable`              | Too many requests for one code or refresh token (30 a minute)                                                                                                                                                            | Wait `Retry-After` seconds, then send the same request again.                                                                                                                                                                   |
| The API answers `401` with `reason: "wrong_audience"`                 | The token was issued for the MCP server                                                                                                                                                                                  | Send `resource=https://taskloader.com/api/v1`.                                                                                                                                                                                  |
| The API answers `403 insufficient_scope`, even right after connecting | The person did not grant a scope the call needs: they can untick any scope on the consent screen                                                                                                                         | Check `credential.scopes` from `GET /me` before calling, as the example does, and send the person through authorization again for what is missing. Approving again adds it to the connection, with no need to disconnect first. |

## Disconnecting

When the person disconnects inside your app, revoke the refresh token, which ends the access tokens issued from it too, and delete what you stored. The answer is `200` with an empty body even when the token had already ended, so a retry is safe:

```bash
curl https://taskloader.com/api/auth/oauth2/revoke \
  --data-urlencode token="$REFRESH_TOKEN" \
  --data-urlencode token_type_hint=refresh_token \
  --data-urlencode client_id="$CLIENT_ID"
```

People can also disconnect your app from Taskloader, in Account settings → Connected apps. Your next request then fails with `401`, and your next refresh with `invalid_grant`: treat both as "disconnected" and offer to connect again, as the example does.

## Going to production

- **Publish a client metadata document** if your app has a website. People then see your verified host instead of **Unverified app**, and you skip registration.
- **Servers can authenticate with `private_key_jwt`** instead of `none`: publish your keys at a `jwks_uri` and sign a client assertion for each token request. See [Client authentication](https://taskloader.com/docs/authentication/oauth.md#client-authentication).
- **Ask for the least access.** Every scope is a line people read before choosing Allow.
- **One refresher per connection.** If several workers share a connection, let one refresh and share the tokens: two refreshes of the same token more than 60 seconds apart revoke it.
