```yaml
product: AlterLab
title: OAuth2 Machine-to-Machine Authentication
comparison_context: "AlterLab is an alternative to Firecrawl, ScrapingBee, and Bright Data."
source_url: https://alterlab.io/docs/guides/oauth2
```

Guide

# OAuth2 Machine-to-Machine Authentication

Connect third-party automation tools to AlterLab using the OAuth2 Authorization Code flow. Designed for server-to-server integrations where a tool needs to act on behalf of a user without storing their password.

Prerequisites

You need an AlterLab account with an active session (NextAuth JWT). OAuth2 is pre-configured for the n8n and Zapier integrations. For custom integrations, [contact support](mailto:support@alterlab.io) to request a client_id and client_secret.

## OAuth2 vs API Keys

AlterLab supports two ways for third-party tools to authenticate: direct API keys and OAuth2. Choose based on your use case.

| Aspect | Direct API Key | OAuth2 |
| --- | --- | --- |
| Setup | Copy from dashboard, paste into tool | One-time browser flow — no copy/paste |
| Credential exposure | Key is visible in tool settings | Short-lived, scoped access token issued only to the server, never shown in the browser |
| Rotation | Manual | Automatic: access tokens expire after one hour and the refresh token rotates on every refresh |
| Best for | Scripts, CI/CD, personal automation | Integrations installed by end users (n8n, Zapier, custom apps) |

Access tokens are not API keys

The `access_token` returned by the OAuth2 token endpoint is an opaque, short-lived bearer token (`alo_at_...`). It expires after `expires_in` seconds (one hour) and is sent as `Authorization: Bearer`. It is not accepted in the `X-API-Key` header. Each token response also carries a 30-day refresh token (`alo_rt_...`) that rotates on every use.

## How It Works

AlterLab implements the standard OAuth2 Authorization Code flow in four steps.

1

### Web app requests an authorization code

The AlterLab web app calls `POST /api/v1/oauth/authorize` with the authenticated user's session JWT and the client's S256 `code_challenge`. AlterLab generates a short-lived (5-minute) authorization code bound to that challenge.

2

### Web app redirects to the third-party callback

The web app appends `?code=...&state=...` to the third-party's redirect_uri and navigates the user there. The third-party receives the code in its callback handler.

3

### Third-party exchanges the code for tokens

The third-party's backend calls `POST /api/v1/oauth/token` with the code, its `code_verifier` and its client credentials. AlterLab checks the verifier against the stored challenge and returns an `access_token`, a `refresh_token` and `expires_in`. No API key is created. The code is consumed atomically — it cannot be replayed.

4

### Third-party calls the API and refreshes

The third-party sends the access token as `Authorization: Bearer` on requests allowed by its scopes. Before the token expires it exchanges the refresh token for a new pair.

## Quick Start

The following examples show the raw API calls. In practice, n8n and Zapier handle these steps automatically through their credential setup wizard.

### Step 1: Get an Authorization Code

PKCE with the S256 method is required for every client. Before starting, the third-party generates a random `code_verifier` (43–128 characters from `A-Z a-z 0-9 - . _ ~`) and keeps it secret. The `code_challenge` is the unpadded base64url SHA-256 hash of the verifier (43 characters).

Python

```
import base64, hashlib, secrets

code_verifier = secrets.token_urlsafe(64)
code_challenge = (
    base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest())
    .rstrip(b"=")
    .decode()
)
```

The web app then calls this endpoint with the user's NextAuth session JWT in the Authorization header and the challenge. No third-party credentials are needed here.

POST

`/api/v1/oauth/authorize`

Bash

```
curl -X POST https://api.alterlab.io/api/v1/oauth/authorize \
  -H "Authorization: Bearer YOUR_NEXTAUTH_JWT" \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": "n8n",
    "redirect_uri": "https://your-n8n.example.com/oauth/callback",
    "state": "random-csrf-token-1234",
    "scope": "scrape",
    "source": "n8n",
    "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM",
    "code_challenge_method": "S256"
  }'
```

Response:

JSON

```
{
  "code": "abc123xyz789...",
  "state": "random-csrf-token-1234"
}
```

| Parameter | Required | Description |
| --- | --- | --- |
| client_id | Yes | Identifier for the third-party app (e.g. `n8n`) |
| redirect_uri | Yes | Where to redirect after authorization. Must be on the allowed-list (`*.alterlab.io` or configured redirect URIs). |
| state | Yes | CSRF protection token. Returned unchanged — verify it matches. |
| scope | No | Space-separated scopes (default: `scrape`). See Scopes. |
| source | No | Human-readable label for the integration, recorded with the authorization. |
| code_challenge | Yes | Unpadded base64url SHA-256 hash of your code_verifier (43 characters). A missing or malformed challenge returns `400` `invalid_request`. |
| code_challenge_method | Yes | Must be `S256`. Any other method returns `400` `invalid_request`. |

### Step 2: Exchange the Code for Tokens

The third-party backend calls this endpoint — no user session required. It sends the authorization code together with the `code_verifier` from step 1 and its client credentials. The pre-configured n8n client sends client_id and client_secret in the JSON body; the endpoint also accepts `application/x-www-form-urlencoded` requests.

POST

`/api/v1/oauth/token`

Bash

```
curl -X POST https://api.alterlab.io/api/v1/oauth/token \
  -H "Content-Type: application/json" \
  -d '{
    "grant_type": "authorization_code",
    "code": "abc123xyz789...",
    "client_id": "n8n",
    "client_secret": "YOUR_CLIENT_SECRET",
    "redirect_uri": "https://your-n8n.example.com/oauth/callback",
    "code_verifier": "YOUR_CODE_VERIFIER"
  }'
```

Response:

JSON

```
{
  "access_token": "alo_at_abc123...",
  "token_type": "bearer",
  "expires_in": 3600,
  "refresh_token": "alo_rt_def456...",
  "scope": "scrape"
}
```

Codes are single-use

Authorization codes are consumed atomically on first use and cannot be replayed. If the token exchange fails after the code was consumed, start the authorize flow again to get a fresh code. Codes expire after 5 minutes if not used. A missing or mismatched code_verifier returns `invalid_grant`.

### Step 3: Call the API with the Access Token

Send the access token in the `Authorization: Bearer` header on any endpoint its scopes allow. OAuth access tokens are only accepted as bearer tokens, never in the `X-API-Key` header.

Bash

```
curl -X POST https://api.alterlab.io/api/v1/scrape \
  -H "Authorization: Bearer alo_at_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com"}'
```

An expired or revoked access token returns `401` with `WWW-Authenticate: Bearer error="invalid_token"`. Refresh the tokens and retry.

### Step 4: Refresh the Tokens

Access tokens expire after one hour. Exchange the refresh token for a new access token and a new refresh token, then store both. The old refresh token is retired; see Token Rotation and Revocation.

Bash

```
curl -X POST https://api.alterlab.io/api/v1/oauth/token \
  -H "Content-Type: application/json" \
  -d '{
    "grant_type": "refresh_token",
    "refresh_token": "alo_rt_def456...",
    "client_id": "n8n",
    "client_secret": "YOUR_CLIENT_SECRET"
  }'
```

Response:

JSON

```
{
  "access_token": "alo_at_ghi789...",
  "token_type": "bearer",
  "expires_in": 3600,
  "refresh_token": "alo_rt_jkl012...",
  "scope": "scrape"
}
```

## Token Rotation and Revocation

Every authorization creates an independent grant with its own access and refresh tokens. Authorizing a second app, or re-authorizing the same one, never invalidates the tokens your other apps hold.

### Short-lived access

Access tokens expire after one hour. The app exchanges its refresh token for a new pair; refresh tokens last 30 days.

### Rotation on every refresh

Each refresh issues a new refresh token and retires the old one. Presenting a retired refresh token again revokes the whole grant.

### Revoke any time

Revoke an app under Settings > Connected Apps, or have the app call the RFC 7009 endpoint `POST /api/v1/oauth/revoke`. Your other apps keep working.

How fast revocation takes effect

Revoking a grant writes a revocation fence that every API replica checks, so its tokens are normally rejected on the next request. If that fence write fails, verified tokens are still cached for at most 60 seconds, so in the worst case a revoked access token is refused within 60 seconds of revocation.

## Scopes

Request only the scopes your integration needs. Combine them with spaces, for example `scrape billing:read`.

| Scope | Access |
| --- | --- |
| scrape | Run scrapes, extraction, crawls, searches, maps, batches and cost estimates, and read the results of your own jobs, crawls and batches. No account or billing access. |
| account:read | Read the identity of the authorized account (`GET /api/v1/auth/identity`). Read-only. |
| billing:read | Read the credit balance (`GET /api/v1/billing/balance`). No payments or changes. |
| sessions | Create and manage your stored browsing sessions; cookie values are never returned. Org sharing, kill-all and health checks stay API key or dashboard only. |

An OAuth access token can call only the endpoints listed for its scopes. Any other endpoint, including API key management, spend limits and payments, answers `403` with `{"error": "insufficient_scope"}` and a `WWW-Authenticate: Bearer error="insufficient_scope", scope="..."` header naming the missing scope. API keys are not affected.

Refreshing never changes scope

A refresh token always returns the scopes originally granted. Sending a different `scope` with `grant_type=refresh_token` is rejected with `invalid_scope`. To get more access, send the user through authorization again so they can approve the new scopes.

## Client Configuration

Register a new OAuth2 client (custom integration) yourself with RFC 7591 dynamic client registration: `POST /api/v1/oauth/register` with your `redirect_uris`. A confidential client (`token_endpoint_auth_method: client_secret_basic`, the default) receives a client_id and client_secret. A public client (`token_endpoint_auth_method: none`, for example a desktop or CLI app) receives only a client_id and must use PKCE. Registering the same public-client metadata again returns the existing client_id.

#### Allowed redirect_uri patterns

- `*.alterlab.io` — always allowed
- Registered clients — exactly the `https` redirect_uris you registered
- `http` loopback (`localhost`, `127.0.0.1`, `[::1]`) with an explicit port — allowed in production for public native clients (`application_type: native`), for example a CLI listening on a local port

Redirect URI validation

The redirect_uri in the token exchange must exactly match the redirect_uri used in the authorize step. A mismatch returns an `invalid_grant` error.

## Error Reference

| Error | HTTP | Cause |
| --- | --- | --- |
| invalid_client | 401 | client_id or client_secret is wrong |
| invalid_grant | 400 | Authorization code is invalid, expired (5-min TTL), or already used |
| unsupported_grant_type | 400 | grant_type is not `authorization_code` or `refresh_token` |
| invalid_request | 400 | Authorize request has no code_challenge, a malformed code_challenge, or a code_challenge_method other than `S256` |
| invalid_grant | 400 | code_verifier is missing or does not match the code_challenge sent in the authorize step |
| invalid_grant | 400 | redirect_uri in token request does not match the one used in authorize |
| OAuth integration is not configured | 503 | Server-side OAuth credentials are missing (contact support) |

[BYOK Extraction](https://alterlab.io/docs/guides/byok-extraction)[Support & Tickets](https://alterlab.io/docs/guides/support)

Last updated: June 2026