# Apps that use Auth0, Okta, Cognito or another sign-in provider

For teams whose users sign in through a provider: Auth0, Okta, Amazon Cognito, Microsoft Entra ID, Keycloak, Clerk,
Firebase Authentication, or any OpenID Connect or SAML service. Read [Accept AI agents in your app](https://docs.allowedby.com/guides/accept-agents)
first; this page explains what changes for you, and what you have to build.

## In one minute

- **Your provider never sees agent requests.** An agent does not sign in. It sends `Allowed-By` and `AllowedBy-Proof`,
  the SDK checks them, and your handler receives a context. No login, no access token from your provider, no session,
  no cookie.
- **The person arrives with a new identifier.** `human_id` is pseudonymous and different for every app. It is not your
  provider's user id (`sub`), and nothing in the request connects the two. You connect them once, while the person
  is signed in to your app: **account linking**.
- **AllowedBy proves who approved what. Your app still decides what that person may touch.** After linking, run the
  same authorisation as for a signed-in user: their account, their role, their organisation.
- **Your provider's controls do not apply to agent requests.** Signing out, resetting a password or MFA, blocking a
  user, and your provider's login rules and logs all act on sign-ins only. Check your own user record on every agent
  request instead.

## What happens to an agent request

```text
agent ── Allowed-By + AllowedBy-Proof ──▶ AllowedBy middleware ──▶ your handler (ctx)
                                           checks the agent, the
                                           person's approval and
                                           this exact request
person ── browser or app, provider token ──▶ your provider's middleware ──▶ your handler (user)
```

| | A signed-in user | An agent through AllowedBy |
|---|---|---|
| Who checks the caller | Your provider (token, session) | The SDK, offline |
| Who the person is | The provider's user id | `ctx.human_id` (pseudonymous, this app only), `ctx.human_iss` (their node) |
| How sure you are of the person | Your provider's login and MFA | `ctx.level`: a passkey tap at the person's node (1), a verified legal identity (2, 3) |
| What they allowed | Everything their role allows | Only the capabilities they approved, with their limits (`ctx.capabilities`, `ctx.display`) |
| Ended by | Sign-out, session expiry, blocking the user | The person withdrawing the approval in their wallet, or its expiry |
| Seen in | Your provider's logs | Your logs: `ctx.agent`, `ctx.operator`, `ctx.gid`, `ctx.rev` |

The SDK never reads the `Authorization` header or your cookies, and never calls your provider.

## 1. Keep agent routes apart from your users' routes

A route of the map is for agents only: a request without AllowedBy headers gets `401` with a challenge, even when it
has a valid token from your provider. And your provider's middleware refuses an agent request, which has no token.
So the two must not share a method and path.

- **Recommended: a path prefix or a host for agents.** Serve the same handlers twice: `/api/...` with your
  provider's middleware, `/agent/...` (or `agents.api.example.com`) with AllowedBy's. Mount the app under the prefix
  so the SDK sees it (`SCRIPT_NAME`, ASGI `root_path`, or `prefix` in `check()`).
- **Your provider's middleware or gateway must not cover the agent paths**, nor the SDK's own endpoints:
  `/.well-known/allowedby` (and `/.well-known/allowedby/tenants/...`), `/openapi.json`, `/.well-known/api-catalog`,
  `/allowedby/callback`, `/allowedby/link`, and `/allowedby/admin` (it has its own token). A
  JWT authoriser on the whole API (an API gateway's Cognito or JWT authoriser, `app.use(auth())`, a gateway plugin)
  answers `401` before AllowedBy sees the request.
- **Do not choose by the presence of a header** (`Authorization` present, so skip AllowedBy). That works only as well
  as your provider's check behind it, and an agent holding a token of your provider then skips the person's approval.
- **Let the headers through.** Proxies must forward `Allowed-By` and `AllowedBy-Proof` unchanged and accept them up to
  8 KiB together (nginx: `large_client_header_buffers`).

## 2. Link the person to their account

Without linking, the only identity you have is `ctx.human_id`. That is enough when the agent's data is its own (notes
the person writes through their agent). It is not enough to reach an account that already exists in your app: the
customer's orders, their organisation's invoices.

Linking pairs `(ctx.human_iss, ctx.human_id)` with your user id, once, while the person is signed in to your app:

1. On a page behind your provider's login, your app makes a one-time code for the signed-in user and shows it with
   the account's handle (a username or account name the person recognises, not a secret).
2. The person gives both to their agent.
3. The agent sends the code to your link route for that account. The person approves that request with their
   passkey; the sentence they sign names the account.
4. Your app checks that the code belongs to that account and stores the pair against the user.

From then on, every agent request of that person resolves to your user: look up `(ctx.human_iss, ctx.human_id)` and
treat the request as theirs.

**Where the link is kept.** In the Python SDK, `link_start()` and `require_link=` do steps 1 to 4 for you, but keep the
links in the memory of one process today: they are lost on restart and not shared between instances. Its link route
(`aby:link`) is also a `write` route whose sentence does not name the account (see the rules below). The other SDKs
do not have linking yet and refuse `requireLink`. In production, in any language, make the link route yourself and keep
the pairs in your database, as below.

```python
"""Account linking for an app whose users sign in through a provider (Flask; the same in any framework).
current_user() is your provider's session; db is your database."""
import hashlib
import os
import secrets
import time

from flask import Flask, abort, g, request

import allowedby.flask
from allowedby import AllowedBy, route

routes = [
    # `write`, as linking is in ABY-3 §6; the handler checks that the sentence the person signed names the account
    route("POST", "/agent/accounts/{account}/link", "account:link", cls="write", level=1,
          resource="account:{account}", summary="Link your AllowedBy identity to your account",
          body={"code": "the code shown in your settings"}),
    route("GET", "/agent/orders", "orders:read", level=1, resource="order:*", summary="List your orders"),
]
LINK = "Link your AllowedBy identity to the Example {scope}"  # {scope} is account:<handle>
templates = {"account:link": LINK,
             "orders:read": "Read your orders"}

app = Flask(__name__)
aby = AllowedBy(origin=os.environ["ALLOWEDBY_ORIGIN"], node=os.environ["ALLOWEDBY_NODE"],
                org={"legal_name": "Example Ltd", "country": "FR"}, routes=routes, templates=templates)
allowedby.flask.AllowedBy(app, aby)


def digest(code):
    return hashlib.sha256(code.encode()).hexdigest()


@app.post("/settings/agents/code")  # behind your provider's login, never under /agent
def new_link_code():
    user = current_user()  # your provider's session
    code = secrets.token_urlsafe(12)
    db.link_codes.put(digest(code), user_id=user.id, expires=time.time() + 600)  # one at a time per user
    return {"account": user.handle, "code": code}  # the person gives both to their agent


@app.post("/agent/accounts/<account>/link")
def link(account):
    ctx = g.allowedby  # verified: the person approved with their passkey...
    if LINK.replace("{scope}", "account:" + account) not in (ctx.display or {}).get("lines", []):
        abort(403)  # ...but not a sentence naming this account (an approval for account:*, say)
    row = db.link_codes.take(digest(str((request.get_json(silent=True) or {}).get("code", ""))))  # deleted when read
    if row is None or row.expires < time.time() or db.users.get(row.user_id).handle != account:
        abort(400)  # unknown, expired, or the code of another account than the one approved
    db.agent_links.put((ctx.human_iss, ctx.human_id), user_id=row.user_id, linked_at=time.time())
    notify(row.user_id, "An AI agent identity was linked to your account")
    return {"linked": True}


@app.get("/agent/orders")
def orders():
    ctx = g.allowedby
    user = db.users.get(db.agent_links.user_for((ctx.human_iss, ctx.human_id)))
    if user is None or user.blocked:  # not linked, or blocked in your app or your provider
        abort(403)
    return {"orders": db.orders.for_user(user.id)}
```

Rules for the link:

- **The code is for the signed-in user only.** Short-lived (minutes), used once, stored hashed, one per user at a
  time. Show it on your own page, never by email or in a URL.
- **The approval names the account.** Put the account's handle in the link route's path and `{scope}` in its
  sentence, and accept the link only when the sentence the person signed (`ctx.display`) names that account. The
  agent asks for this approval itself (the route is `write`, as linking is in ABY-3 §6), so it could ask for every
  account at once (`account:*`): the sentence would then not name one, and the handler refuses it. A handle is 1 to
  64 letters, digits, `.`, `_` or `-`, and not `.` or `..` (no email address), or the challenge cannot name it. Otherwise anyone who slips their own code to the person's
  agent (a message, a web page the agent reads) gets that person's agent requests, and what the agent writes, in
  their own account. Tell your users to give their agent only a code from their own settings page.
- **A wrong code still costs a tap.** Your handler sees the code only after the person approved. Rate-limit the link
  route per agent and per person, and tell the person when a code was refused.
- **Say what happened.** Notify the user when an identity is linked, list the linked identities in their settings,
  and let them remove one. Whoever gets a user's code can link their own passkey to that account.
- **Never link by email.** The same email at your provider and at the person's node does not prove the same person
  controls both. Ask for the code even when the node discloses a verified email.
- **Key on both values.** `human_id` is only unique together with `human_iss`, the person's node.
- **One person can have several identities.** A person who uses two nodes, or who loses every passkey and starts again
  without recovering their identity, arrives with a new `human_id`: they link again.
- **Each of your origins sees a different `human_id`.** If agents call `api.example.com` and `eu.api.example.com`,
  the same person has two ids. Link per origin, or give agents one origin.

## 3. Sign-out, blocking and deletion

Approvals live at the person's node, not in your provider. Nothing your provider does ends them.

| In your provider | What happens to agent requests | What to do |
|---|---|---|
| The user signs out, or their session expires | Nothing: they continue | Nothing. Approvals are withdrawn in the person's wallet. |
| Password or MFA reset | Nothing | Nothing. |
| User blocked or suspended | Nothing, unless your app checks | Check your user's status on every agent request (the `orders()` handler above). |
| User deleted | Nothing, unless your app checks | Delete their links. Unlinked requests no longer reach the account. |
| Role or organisation changed | Your authorisation decides | Read the role from your database at request time, never from a copy made at linking. |

## 4. Levels are not your provider's MFA

`ctx.level` says how the person's node knows them: a passkey tap with user verification (1), a legal identity checked
at eIDAS substantial (2) or high, on a hardware passkey (3). Your provider's MFA, social logins and passwordless
flows do not count, and your own customer checks do not raise it. Choose each route's level as if you knew nothing
else about the person. A route that needs your own checks too (a verified customer, a signed contract) requires the
link, then checks your record.

## 5. Companies: SSO, organisations, tenants

If your provider handles organisations (enterprise SSO, Auth0 Organizations, Okta or Entra tenants, Cognito groups):

- **The tenant in the path is not proof of membership.** An approval for `/t/{tenant}/...` means the person approved
  that action for that tenant. It does not mean they belong to it. Your authorisation checks it, from the link, as for
  a signed-in user. In the Python SDK: `link_authorize(account, route, params)`.
- **Company mandates** (`ctx.acting_for`) come from the company's own node, which signs who may act for it. A company
  can feed that node from its identity provider: SCIM for members and teams, OpenID Connect sign-in at enrolment
  ([Use AllowedBy as a company](https://docs.allowedby.com/guides/use-allowedby)). Its provider is not yours: compare `acting_for.org` with the
  organisation you know, never a name.

## 6. Tokens agents already have

If agents already reach your API with tokens from your provider (machine-to-machine clients, personal API keys,
OAuth tokens a user granted), those requests keep working and never ask the person: AllowedBy does not see them.
Decide for each:

- **Keep them** for integrations that do not act for a person.
- **Narrow them** to what may run without a person's approval.
- **Retire them** for actions a person must approve: point those agents to the agent routes.

## 7. Personal data

Your provider holds your user's profile. An agent request carries none of it: no name, email or phone. Once linked,
read your own record. Without a link, ask the person through disclosure, with a purpose
([Personal data](https://docs.allowedby.com/guides/accept-agents#9-personal-data-purpose-and-the-disclosure-key)). Never copy one into the other without
the person's consent.

## 8. Audit and limits

- **Logs.** Your provider's logs show no agent request. Log in your app: `ctx.agent`, `ctx.operator`, `ctx.human_id`,
  `ctx.gid`, `ctx.rev`, the route and your user id once linked. The SDK's audit sink can do it.
- **Attack protection.** Your provider's brute-force and bot protection does not see agent requests. Rate-limit the
  agent routes yourself, by `ctx.agent` and by user.
- **Tests.** Test the agent routes without a browser or a node (the "Testing" section of each language guide), and
  test that each agent route refuses a request with only your provider's token.

## Checklist

| # | Before agents reach real accounts | Section |
|---|---|---|
| 1 | Agent routes on their own prefix or host; your provider's middleware off those paths and off the SDK's endpoints. | 1 |
| 2 | Proxies forward `Allowed-By` and `AllowedBy-Proof`, up to 8 KiB. | 1 |
| 3 | Link route and link codes in your database, keyed on `(human_iss, human_id)`; the approval names the account; notify, list, unlink. | 2 |
| 4 | Every agent handler looks up the linked user and refuses when there is none or when the user is blocked. | 2, 3 |
| 5 | Deleting a user deletes their links. | 3 |
| 6 | Authorisation (account, role, tenant) from your database, exactly as for a signed-in user. | 2, 5 |
| 7 | Levels chosen without counting your provider's MFA. | 4 |
| 8 | Each existing agent token kept, narrowed or retired. | 6 |
| 9 | Agent requests logged and rate-limited in your app. | 8 |
