OAuth
Build an app that users connect to their Protokol project, so it can call the Protokol API on their behalf. Protokol uses the standard OAuth 2.0 authorization code flow with PKCE.
Coming from the Protokol Toolkit?
If you landed here after ptkl profile auth in your browser, you are already signed in. You can close this tab and return to your terminal. This guide is for building your own app on Protokol OAuth.
How it works
Your app Browser / user Protokol
| | |
| 1. send user to /v1/oauth/authorize (client_id, project_id, scope,
| state, code_challenge) -->|--------------------------->|
| | 2. user signs in, reviews and approves
|<-- 3. redirect to your redirect_uri ?code=...&state=...&iss=... --|
| |
| 4. POST /v1/oauth/token (code, code_verifier) ----------->|
|<-- access_token (+ refresh_token with offline_access) ----|
| |
| 5. call the API: Authorization: Bearer <access_token> --->|
| 6. when it expires: POST /v1/oauth/token (refresh_token) >|
Want users to sign in to your app with their Protokol account? See Sign in with Protokol (OpenID Connect).
Building a website or app that people open from Protokol and sign in to? Create a web app instead: see Web apps. This page is the reference for OAuth clients, the credentials used by integrations such as scripts, CLIs and servers.
Key facts:
- A token is issued for one user in one project. You can send the
project_idin the authorization request; if you leave it out, Protokol asks the user to choose a project when needed. - The user sees a consent screen listing exactly what your app can do and approves or denies it.
- Access tokens are short-lived (15 minutes by default). Use a refresh token to get new ones without asking the user again.
- Only the S256 PKCE method and the
coderesponse type are supported.
All endpoints below are relative to the API host. In examples we use https://lemon.protokol.io; fetch the discovery document to get the exact endpoint URLs and issuer for your environment.
Register an app
- Sign in to the Protokol dashboard as a project admin.
- Open OAuth in the sidebar and choose Clients, then Create client. User-facing apps with a Launch URL are created under Developer → Web apps instead.
- Fill in the form:
| Field | Description |
|---|---|
| Name | Shown to users on the consent screen |
| Client type | Public for code that cannot keep a secret (single-page apps, mobile apps, CLIs). Confidential for server-side code that can keep a secret |
| Access type | User connection acts as the signed-in person. Project installation acts for the project and requires a confidential client |
| Application type | Web or Native (decides which redirect URIs are accepted) |
| Redirect URIs | Exact callback URIs your app uses |
| Allowed permissions | The most your app may ever request (exact permissions, optionally patterns) |
| Allow refresh tokens | Required if your app will request offline_access |
| Token policy | Optional: access token lifetime (60 to 900 seconds) and, for public clients, refresh token lifetime (1 hour to 30 days) |
| Metadata | Optional logo, homepage, terms and privacy URLs shown on the consent screen |
- Save. For a confidential client the client secret is shown once. Copy it into your secret store immediately. You can rotate it later from the client's page; the previous secret keeps working for the grace period you configured.
The client gets an id of the form pk_cli_….
Redirect URI rules
- Web apps: an exact
https://URI. No wildcards and no fragments. - Native apps: an
https://app link, a reverse-domain scheme such ascom.example.app:/callback, or a loopback URIhttp://127.0.0.1:PORT/path/http://[::1]:PORT/pathwith an exact registered path (the port may vary). - A registered URI cannot contain the query parameters
code,error,stateoriss; Protokol adds those to the callback.
Public clients
A client is project-only by default. A public client, such as a CLI, a mobile app or a desktop app that users of other projects sign in to, is different: it needs review and an install by a project admin, like a public web app.
- Set the client's visibility to Public and choose Request publication. Protokol reviews it.
- After approval the client appears in the marketplace under Tools, with an Install button for project admins. It has no Open button and is not shown on the home screen, because it has no Launch URL.
- A project admin installs it, optionally limiting it to some workspaces. Members of that project can then sign in to it; a member sees a message asking them to contact an admin until it is installed. When someone signs in to a project that has not installed the client yet, an admin can install it on the consent screen.
Uninstalling revokes the access of the project's members. The rules for installing and workspace access are the same as for web apps.
Project-only apps and publication
A new client works only in the project that owns it. This is how you add your own trusted app to your own project.
To let users connect your app in other projects, request publication:
- Open the client in the dashboard (OAuth → Clients → Edit).
- In the Publication section choose Request publication.
- The approval status changes to Pending review until Protokol approves it.
| Approval status | Meaning |
|---|---|
| Not requested | Project-only |
| Pending review | Waiting for Protokol. Other projects cannot authorize it yet |
| Approved | Any project can authorize the app (subject to that project's own app policy) |
| Rejected | Not approved. You can edit and request again |
| Suspended | Blocked by Protokol. Existing tokens stop working on their next request |
Note
After approval, changing the name, logo, homepage, terms or privacy URLs, redirect URIs, or widening the allowed permissions sends the client back to review. Narrowing permissions and rotating the secret do not. You can Withdraw publication at any time; the app becomes project-only again.
Project admins can also restrict which apps their members may connect (OAuth → App policy). If your app is published, ask admins to add it to their allow-list when a project uses that policy.
Scopes
A request lists the permissions your app wants. Each permission is a Protokol permission name such as read products, encoded for the scope parameter. Scopes are space-delimited and case-sensitive.
| Form | Meaning |
|---|---|
perm64:<value> |
One permission. <value> is the base64url encoding (no = padding) of the UTF-8 permission name |
pattern64:<value> |
A pattern. <value> is the base64url encoding of a regular expression that is matched against the whole permission name |
offline_access |
Plain token. Asks for a refresh token. Not a permission |
openid, profile, email |
Plain tokens for Sign in with Protokol. Not permissions |
Examples:
| Permission | Scope token |
|---|---|
read products |
perm64:cmVhZCBwcm9kdWN0cw |
edit products |
perm64:ZWRpdCBwcm9kdWN0cw |
dev env_access |
perm64:ZGV2IGVudl9hY2Nlc3M |
(read|create) products (pattern) |
pattern64:KHJlYWR8Y3JlYXRlKSBwcm9kdWN0cw |
A complete scope value, URL-encoded in the authorize request:
Rules:
- Patterns are only accepted at authorization time and are expanded to the exact permissions that exist. A bare
.*is rejected. Refresh requests acceptperm64only. - What the user actually grants is the intersection of what you request, what your client is allowed to request, and what the signed-in user can do in that project, minus any permission the user unticks on the consent screen. The token response
scopelists the final permissions asperm64:tokens; always read it instead of assuming you got everything you asked for. - If you omit
scope, your client's whole allowed-permissions list is requested. - Permissions the user does not hold are shown on the consent screen as not available and are not granted.
- Permission names are listed in the dashboard's permission picker when you create a client.
API users created by your app
An app can create API users and secrets (POST /v1/user/api-user) only if the token holds edit base_users and credentials::manage base_users.
- The new API user can only get roles whose permissions the token itself holds. Admin roles are never allowed; the call fails with
403andinsufficient_scope. - API users and secrets your app creates are not revoked when the user disconnects the app. They are listed under the app's credentials in Connected apps and must be deleted separately.
Authorization code with PKCE
1. Create a PKCE verifier and challenge
For every login, generate a random code_verifier (43 to 128 characters) and send its SHA-256 hash as the code_challenge.
import { randomBytes, createHash } from "node:crypto"
const b64url = (buf) => buf.toString("base64url")
const codeVerifier = b64url(randomBytes(32)) // 43 chars
const codeChallenge = b64url(createHash("sha256").update(codeVerifier).digest())
const state = b64url(randomBytes(16))
// keep codeVerifier and state in the user's session; send only the challenge
import base64, hashlib, secrets
def b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
code_verifier = b64url(secrets.token_bytes(32)) # 43 chars
code_challenge = b64url(hashlib.sha256(code_verifier.encode()).digest())
state = b64url(secrets.token_bytes(16))
# keep code_verifier and state in the user's session; send only the challenge
2. Send the user to authorize
GET https://lemon.protokol.io/v1/oauth/authorize
?response_type=code
&client_id=pk_cli_0123456789abcdef0123456789abcdef
&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback
&project_id=YOUR_PROJECT_ID
&state=STATE_FROM_STEP_1
&code_challenge=CHALLENGE_FROM_STEP_1
&code_challenge_method=S256
&scope=perm64%3AcmVhZCBwcm9kdWN0cw%20offline_access
| Parameter | Required | Notes |
|---|---|---|
response_type |
yes | code |
client_id |
yes | Your pk_cli_… id |
redirect_uri |
yes | Must exactly match a registered URI |
project_id |
no | UUID of the project the user connects your app to. The token is bound to it, and the user cannot pick a different project on the consent screen. If you omit it, see Choosing the project |
state |
yes | Opaque value you verify on return (CSRF protection) |
code_challenge |
yes | PKCE challenge |
code_challenge_method |
yes | S256 |
scope |
no | See Scopes. Must not be empty if present |
The user signs in if needed, reviews the consent screen ("Your app wants to connect to Project") and approves or denies it. The user can untick individual permissions before approving; your app then gets only the ticked ones. Repeating a request the user has already approved skips the screen when the requested access is covered. A request for a permission the user unticked earlier shows the screen again.
Choosing the project
project_id is optional. When you send it, Protokol uses that project. When you leave it out, Protokol picks the project for you:
- Protokol only considers projects where your app is installed (a project that owns the app counts as installed). If the user can use your app in only one project, that project is used.
- If the user has already connected your app in exactly one of their projects, that project is used.
- If the user can choose between several projects, Protokol shows a project picker before the consent screen.
- If your app is not installed in any of the user's projects, the request fails with
access_denied. Tell those users to install your app from the Protokol marketplace, or to ask a project admin to. An explicitproject_idstill lets a project admin install the app from the consent screen.
Your app does not need to handle the picker: the user comes back to your redirect_uri as usual. The token response tells you which project was chosen (see below). Apps that already send project_id keep working unchanged, and a user who arrives from the marketplace launch is not asked again if you forward the project_id you received (see Web apps).
3. Handle the redirect
On success Protokol redirects to your redirect_uri:
Before you use the code:
- Check that
stateequals the value you stored. - Check that
issequals the issuer from the discovery document (RFC 9207). Reject the response if it is missing or different.
The iss parameter is also present on error redirects. The code is single-use and expires after 10 minutes.
4. Exchange the code for tokens
The token endpoint takes application/x-www-form-urlencoded bodies (not JSON).
curl -X POST https://lemon.protokol.io/v1/oauth/token \
-u 'pk_cli_0123456789abcdef0123456789abcdef:YOUR_CLIENT_SECRET' \
-d grant_type=authorization_code \
-d code=pk_ac_CODE_FROM_REDIRECT \
-d redirect_uri=https://app.example.com/callback \
-d code_verifier=VERIFIER_FROM_STEP_1
Instead of HTTP Basic you can send client_id and client_secret as form fields. Use one method, not both.
Response:
{
"access_token": "eyJ…",
"token_type": "Bearer",
"expires_in": 900,
"refresh_token": "pk_rt_…",
"scope": "perm64:cmVhZCBwcm9kdWN0cw perm64:ZGV2IGVudl9hY2Nlc3M offline_access",
"project_id": "YOUR_PROJECT_ID"
}
project_id is the project the token is bound to. Read it when you did not send a project_id in the authorize request, and store it next to the tokens.
redirect_uri must be identical to the one in the authorize request. refresh_token is present only when you asked for offline_access and the client allows it. Token responses are sent with Cache-Control: no-store.
Refresh tokens
Request offline_access to receive a refresh token. Without it the app gets one access token and must send the user through authorization again when it expires.
curl -X POST https://lemon.protokol.io/v1/oauth/token \
-d grant_type=refresh_token \
-d client_id=pk_cli_0123456789abcdef0123456789abcdef \
-d refresh_token=pk_rt_CURRENT_REFRESH_TOKEN
Confidential clients authenticate with their secret instead (-u 'CLIENT_ID:YOUR_CLIENT_SECRET'). You may add scope= with a subset of the permissions you already hold, as perm64: tokens, to get a narrower access token.
Behaviour depends on the client type:
| Public client | Confidential client | |
|---|---|---|
| Authenticates with | client_id and the refresh token |
Client secret and the refresh token |
| Refresh token on each use | Rotated. The response contains a new refresh_token; store it and discard the old one |
Not rotated. The response has no refresh_token; keep the one you have |
| Reusing an old refresh token | Fails with invalid_grant and ends the whole session; the user must authorize again |
Not applicable |
| Lifetime | 30 days absolute from the original authorization (configurable per client between 1 hour and 30 days) | 90 days without use; each refresh restarts the 90 days |
Public clients: store the new refresh token before you use it
Rotation means the old token is spent as soon as you use it. If a request is retried with the old token, or two tabs refresh at the same time, the second attempt looks like token reuse and revokes the session. Serialise refreshes (one at a time per session) and persist the new token immediately.
A refresh also stops working if the user disconnects your app, leaves the project, loses the permissions, or the client is disabled or suspended. Treat invalid_grant on refresh as "sign the user in again".
Call the API
Send the access token as a bearer token:
- The token is bound to the project chosen at authorization. You do not send a project header; calls always act in that project. To work in another project, authorize again with that
project_id. - A call succeeds only if the token's scope contains the permission the endpoint needs.
- The environment defaults to
live. To target another environment sendX-Project-Env.
Non-live environments need dev env_access
Dev requests fail with 403 unless the token includes dev env_access
Requests that send X-Project-Env: dev (or any non-live environment) are rejected unless the token's scope includes the dev env_access permission. Add it to your client's Allowed permissions, request it in scope, and make sure the signing-in user holds it. Tokens issued without it can only use live.
# scope must include perm64:ZGV2IGVudl9hY2Nlc3M (dev env_access)
curl https://lemon.protokol.io/v1/YOUR_ENDPOINT \
-H "Authorization: Bearer ACCESS_TOKEN" \
-H "X-Project-Env: dev"
Without it you get:
HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer error="insufficient_scope"
{"status":false,"code":1000,"message":"Access to env not allowed."}
Because the user can only grant what they hold, a user whose role lacks dev env_access cannot give your app dev access. The token response scope shows what was actually granted.
Revoke a token
Call this when the user signs out of your app.
curl -X POST https://lemon.protokol.io/v1/oauth/revoke \
-d client_id=pk_cli_0123456789abcdef0123456789abcdef \
-d token=pk_rt_REFRESH_TOKEN
Confidential clients authenticate with their secret. The token may be an access token or a refresh token (token_type_hint is optional).
- Revoking a refresh token revokes the whole session, including access tokens already issued from it.
- Revoking an access token revokes only that token.
- A well-formed unknown token returns
200with an empty body, as does a successful revoke. You can only revoke tokens that belong to your client.
Users and project admins can also disconnect apps from the dashboard (OAuth → Connected apps, and Authorized apps in the account menu).
Introspect a token
Confidential clients can check a token they issued:
curl -X POST https://lemon.protokol.io/v1/oauth/introspect \
-u 'pk_cli_0123456789abcdef0123456789abcdef:YOUR_CLIENT_SECRET' \
-d token=ACCESS_OR_REFRESH_TOKEN
{
"active": true,
"scope": "perm64:cmVhZCBwcm9kdWN0cw",
"client_id": "pk_cli_0123456789abcdef0123456789abcdef",
"token_type": "Bearer",
"exp": 1790000000,
"iat": 1789999100,
"sub": "…",
"iss": "https://lemon.protokol.io",
"project_id": "…",
"access_type": "user"
}
An unknown, expired, revoked or foreign token returns exactly {"active": false}. Public clients cannot introspect; the call fails with 401 invalid_client.
Discovery
The authorization server metadata (RFC 8414) is public:
{
"issuer": "https://lemon.protokol.io",
"authorization_endpoint": "https://lemon.protokol.io/v1/oauth/authorize",
"token_endpoint": "https://lemon.protokol.io/v1/oauth/token",
"revocation_endpoint": "https://lemon.protokol.io/v1/oauth/revoke",
"introspection_endpoint": "https://lemon.protokol.io/v1/oauth/introspect",
"response_types_supported": ["code"],
"grant_types_supported": ["authorization_code", "refresh_token"],
"code_challenge_methods_supported": ["S256"],
"token_endpoint_auth_methods_supported": ["none", "client_secret_basic", "client_secret_post"],
"revocation_endpoint_auth_methods_supported": ["none", "client_secret_basic", "client_secret_post"],
"introspection_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post"],
"scopes_supported": ["offline_access"],
"authorization_response_iss_parameter_supported": true
}
Read issuer and the endpoint URLs from this document instead of hard-coding them. authorization_response_iss_parameter_supported: true tells clients that the iss check is expected.
Errors
Authorization errors
If the client_id or redirect_uri is invalid, Protokol shows an error page (HTTP 400) and does not redirect, so a bad request cannot send users to an unregistered address. Fix the request; there is nothing to handle in your callback.
Once the redirect URI is validated, problems come back to your callback as query parameters, always with your state and iss:
https://app.example.com/callback?error=access_denied&state=STATE&iss=https%3A%2F%2Flemon.protokol.io
error |
Cause | What to do |
|---|---|---|
access_denied |
The user declined, or you sent no project_id and none of the user's projects can use your app |
Show a "not connected" state; do not retry automatically |
invalid_request |
Missing or malformed parameter, or an unsupported PKCE method | Fix the request |
invalid_scope |
A scope is malformed, empty, or not allowed for the client | Fix the scope or the client's allowed permissions |
unauthorized_client |
The client may not be authorized here: not published for this project, suspended, blocked by the project's app policy, or a project installation with a public client | Request publication, ask a project admin to allow the app, or use the right client type |
If the service is temporarily unavailable or rate-limited, the authorize endpoint responds with 503 or 429 (with Retry-After) instead of redirecting. Wait and send the user through again.
Token, revoke and introspect errors
These endpoints return a JSON body and Cache-Control: no-store:
| Status | error |
Meaning | What to do |
|---|---|---|---|
| 400 | invalid_request |
Missing or repeated parameter, wrong content type, malformed token or client id, or a client identifier missing from a revoke request | Fix the request. The body must be application/x-www-form-urlencoded |
| 400 | unsupported_grant_type |
Not authorization_code or refresh_token |
Use a supported grant |
| 400 | invalid_grant |
Code or refresh token is invalid, expired, already used, revoked, or the PKCE verifier or redirect_uri does not match |
Start a new authorization. Never retry the same code |
| 400 | invalid_scope |
Requested scope exceeds what was granted | Ask for a subset |
| 400 | unauthorized_client |
The client may not use this grant | Check the client configuration |
| 401 | invalid_client |
Unknown or inactive client, wrong secret, or a public client calling introspection | Check the id and secret. Basic-auth failures include WWW-Authenticate: Basic realm="oauth" |
| 429 | temporarily_unavailable |
Rate limit | Wait for Retry-After seconds, then retry |
| 503 | temporarily_unavailable |
Temporary outage. No token was issued and the grant was not invalidated | Wait for Retry-After (5 seconds by default) and retry with the same request. Use backoff |
Note
A 503 from the token endpoint is never reported as invalid_grant, so you can safely retry a code exchange or refresh after the delay. Do not delete the user's stored tokens on a 5xx.
API call errors
Resource requests fail with a WWW-Authenticate header that tells you what to do:
| Status | WWW-Authenticate |
Meaning | What to do |
|---|---|---|---|
| 401 | Bearer error="invalid_token" |
The access token is expired, revoked, or the grant was disconnected | Refresh once and retry. If refresh fails with invalid_grant, send the user through authorization again |
| 403 | Bearer error="insufficient_scope" |
The token lacks the permission the endpoint needs, or the environment is not allowed (see dev env_access) |
Request the missing permission in a new authorization |
| 503 | none, with Retry-After |
Temporary outage while checking the token | Retry after the delay |
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error="invalid_token"
{"status":false,"code":0,"message":"invalid OAuth token"}
Adding permissions later always needs the user's consent: run the authorization flow again with the larger scope.
Checklist
- Use
S256PKCE and a fresh verifier andstatefor every login. - Verify
stateandisson the callback. - Store refresh tokens like passwords. Never put a client secret in a browser or mobile app; use a public client there.
- Public clients: replace the stored refresh token after every refresh and never refresh concurrently.
- Request only the permissions you need, and include
dev env_accessif you call non-live environments. - Revoke the refresh token when the user signs out.