OAuth Client Credentials and delegated PKCE
Exchange backend credentials or obtain explicit user consent with Authorization Code and S256.
Both flows use POST /api/integrations/oauth/connect/token. The token endpoint authenticates the client or authorization code; it does not require an existing IntegrationBearer token. An issued short-lived access_token is then used as IntegrationBearer for supported business reads. No refresh token, offline access, ID token, general SSO, password grant or implicit flow is offered.
Backend: Client Credentials
Enable Client Credentials in the application's Access area and approve Businesses.View. Register a backend confidential client, explicitly select that scope and save the client ID and one-time secret privately. A backend-only client has no redirect URI.
Send a URL-encoded form with client authentication in the body or Basic header. Do not combine an existing Bearer token with this exchange:
POST https://api.prastav.io/api/integrations/oauth/connect/token
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&client_id=EXAMPLE_CLIENT_ID&client_secret=EXAMPLE_SECRET_REPLACE_ME&scope=Businesses.View
The response uses access_token, token_type, expires_in and scope. In Scalar, use the token operation's form fields with no Bearer authentication. In Postman, choose OAuth 2.0 → Client Credentials, enter the exact token URL and scope, and keep client authentication private. For GET Businesses, select IntegrationBearer and paste only access_token.
The legacy JSON token exchange remains supported for compatible confidential clients. Its body has grantType, clientId, clientSecret; its response has camel-case accessToken, tokenType, expiresIn, appId. Do not confuse it with the standard form response.
Delegated: Authorization Code with PKCE S256
Enable Authorization Code in Access and approve Businesses.View.
Register a user-authorized client with that explicit scope. Select native public, public web or confidential web according to where the app runs. Public clients receive no secret. All authorization-code clients require S256.
Register the exact callback. Native public clients can use HTTP loopback IP; web clients require HTTPS. The native HTTP port exception does not permit changing scheme, IP, path or query. Native HTTPS loopback callbacks are rejected.
Create an unpredictable state and a 43–128-character PKCE verifier. Compute the base64url, unpadded SHA-256 challenge.
Open the authorization operation in the user's browser:
GET https://api.prastav.io/api/integrations/oauth/authorize
?response_type=code
&client_id=EXAMPLE_CLIENT_ID
&redirect_uri=EXACT_REGISTERED_CALLBACK
&scope=Businesses.View
&state=UNPREDICTABLE_STATE
&code_challenge=S256_CHALLENGE
&code_challenge_method=S256
Prastav asks the person to sign in and review the requesting application, publisher information, account, workspace and requested permission. Signing in does not grant access by itself. If the person changes accounts, they must review the request again for that account. Publisher information is supplied by the application and is not a verification badge.
The review shows the full account name, email and workspace, along with the application and client registration IDs. Use Change account if the displayed account is wrong. Review Read businesses, then choose Deny or Authorize in the authentication action row. The footer explains where to revoke access later.
Approval creates the authorization; denial returns the corresponding outcome without granting access. Restart an invalid, expired or already used request from your application. Requests and reviews expire after five minutes. Authorization codes expire after two minutes and can be used only once.
Verify callback state before exchanging the code. When issuer metadata is returned, validate it against the configured API origin. Send the original redirect and verifier:
POST https://api.prastav.io/api/integrations/oauth/connect/token
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&client_id=EXAMPLE_CLIENT_ID&code=RETURNED_CODE&redirect_uri=EXACT_REGISTERED_CALLBACK&code_verifier=ORIGINAL_VERIFIER
A confidential web client also authenticates using its secret. A public client sends none. Never log callback URLs, codes, state, verifier or tokens. Successful authorization continues to the registered callback, without a second grant step. In Postman choose Authorization Code + PKCE S256 and register the exact HTTPS callback Postman actually uses.
Native Python test
The standard-library sample below binds only 127.0.0.1, verifies callback state and issuer, retains tokens only in memory, and retests the same token after consent revocation. Save it as pkce-client.py. Register a native public client with http://127.0.0.1:45112/callback, then run:
python pkce-client.py --client-id YOUR_PUBLIC_CLIENT_ID
For local development, add --api https://localhost:API_PORT with a trusted local certificate. Do not disable TLS verification. The test prints business data to the terminal; use controlled records and do not capture private results in shared logs.
#!/usr/bin/env python3
"""In-memory native public OAuth test client. Register the printed loopback redirect first."""
import argparse
import base64
import hashlib
import http.server
import json
import secrets
import time
import urllib.error
import urllib.parse
import urllib.request
import webbrowser
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--api", default="https://api.prastav.io")
parser.add_argument("--client-id", required=True)
parser.add_argument("--port", type=int, default=45112)
args = parser.parse_args()
origin = urllib.parse.urlsplit(args.api)
if origin.scheme != "https" or not origin.netloc or origin.username or origin.query or origin.fragment or origin.path not in ("", "/"):
parser.error("--api must be an HTTPS origin; use a locally trusted certificate for development")
api = args.api.rstrip("/")
verifier = secrets.token_urlsafe(64)
state = secrets.token_urlsafe(32)
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest()).rstrip(b"=").decode("ascii")
callback = f"http://127.0.0.1:{args.port}/callback"
outcome = {}
class Callback(http.server.BaseHTTPRequestHandler):
def log_message(self, *_):
pass # Callback URLs contain authorization codes; never log them.
def do_GET(self):
target = urllib.parse.urlsplit(self.path)
fields = urllib.parse.parse_qs(target.query, keep_blank_values=True)
valid = target.path == "/callback" and len(fields.get("state", [])) == 1 and secrets.compare_digest(fields["state"][0], state)
issuer = fields.get("iss", [])
if issuer and (len(issuer) != 1 or issuer[0].rstrip("/") != api):
valid = False
self.send_response(200 if valid else 400)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Referrer-Policy", "no-referrer")
self.end_headers()
self.wfile.write(b"Return to the test client." if valid else b"Invalid callback.")
if valid and not outcome:
if len(fields.get("code", [])) == 1 and "error" not in fields:
outcome["code"] = fields["code"][0]
else:
outcome["error"] = fields.get("error", ["invalid_callback"])[0]
with http.server.HTTPServer(("127.0.0.1", args.port), Callback) as server:
server.timeout = 1
url = api + "/api/integrations/oauth/authorize?" + urllib.parse.urlencode({
"client_id": args.client_id, "redirect_uri": callback, "response_type": "code",
"scope": "Businesses.View", "state": state, "code_challenge": challenge, "code_challenge_method": "S256"})
print(f"Registered native public redirect must be {callback}")
print("Opening Prastav sign-in and explicit consent. Tokens stay in memory.")
if not webbrowser.open(url):
raise SystemExit("Unable to open a browser. Configure a default browser and retry.")
deadline = time.monotonic() + 300
while not outcome and time.monotonic() < deadline:
server.handle_request()
if "code" not in outcome:
raise SystemExit("Authorization denied or timed out: " + outcome.get("error", "timeout"))
body = urllib.parse.urlencode({"grant_type": "authorization_code", "client_id": args.client_id,
"redirect_uri": callback, "code": outcome.pop("code"), "code_verifier": verifier}).encode("ascii")
request = urllib.request.Request(api + "/api/integrations/oauth/connect/token", data=body,
headers={"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"})
try:
with urllib.request.urlopen(request, timeout=30) as response:
tokens = json.load(response)
request = urllib.request.Request(api + "/api/businesses?page=1&pageSize=10",
headers={"Authorization": "Bearer " + tokens["access_token"], "Accept": "application/json"})
with urllib.request.urlopen(request, timeout=30) as response:
businesses = json.load(response)
print(json.dumps(businesses, indent=2, ensure_ascii=False))
print("Read succeeded. Revoke this client's access in My Account > Sign-in and security > Authorized applications.")
input("Revoke the latest consent in Prastav, then press Enter to retest...")
try:
with urllib.request.urlopen(request, timeout=30) as response:
print(f"Same-token retest: HTTP {response.status} (unexpected)")
except urllib.error.HTTPError as error:
print(f"Same-token retest: HTTP {error.code}")
except urllib.error.HTTPError as error:
# Do not dump response payloads or token/authorization requests.
raise SystemExit(f"API returned HTTP {error.code}; inspect sanitized server diagnostics if needed.") from None
if __name__ == "__main__":
main()
Token lifetime and revocation
Use the returned expires_in; reauthorize after expiry. An application or credential cannot gain scope through token reuse. Revoking the client or delegated consent invalidates affected existing tokens immediately, including the same token already used successfully. My Account authorization management remains available even when ordinary workspace business access is restricted. See security and troubleshooting for 401, 403 and redirect failures.