# Login with Arizu

Login with Arizu lets people sign in to your app with their Arizu account, the same account they use for the Arizu tester program. It is standard OpenID Connect: the authorization code flow with PKCE. Any certified OpenID Connect library works if you point it at the discovery address.

People sign in to their Arizu account with Google. Your app never sees their Google password, and Arizu never sees anything your app stores.

## Before you start

1. Ask the Arizu team for a client, or add one yourself in the office under Arizu accounts, Sign-in apps.
2. Choose the type:
   - **Server app**: a website or backend that can keep a secret. It gets a `client_id` and a `client_secret`. The secret is shown once, so store it right away.
   - **Phone, desktop or browser app**: it cannot keep a secret, so it gets only a `client_id` and proves itself with PKCE.
3. Register every return address (`redirect_uri`). Arizu only sends people back to an exact match.
4. Choose which scopes the app may ask for.

PKCE with `S256` is required for every app, server apps included.

## Endpoints

| What | Address |
|---|---|
| Discovery | `https://arizu.id/.well-known/openid-configuration` |
| Issuer (`iss`) | `https://arizu.id` |
| Authorization | `https://arizu.id/account/oauth/authorize` |
| Token | `https://arizu.id/account/oauth/token` |
| User info | `https://arizu.id/account/oauth/userinfo` |
| Signing keys (JWKS) | `https://arizu.id/account/oauth/jwks` |
| Revocation | `https://arizu.id/account/oauth/revoke` |
| Sign-out | `https://arizu.id/account/oauth/logout` |

## Scopes and claims

| Scope | What the app gets |
|---|---|
| `openid` | Required. `sub`, the Arizu account ID: 20 lowercase hex characters that never change. Use it as your user ID. |
| `profile` | `name`, `picture` (an https address, only when the person has a photo) and `updated_at`. |
| `email` | `email` and `email_verified` (always `true`: the address comes from Google). |
| `roles` | `roles`, a list such as `["tester"]`. Known roles: `tester`, `beta`, `staff`. |
| `office` | `office`, the person's access to this app as an arizu.id office admin: `{"admin": true, "level": 2, "group": "Editor", "super": false}`. `level` is 0 no access, 1 read only, 2 write, 3 everything, set per app in the office. Only for Arizu's own apps. |
| `offline_access` | A refresh token, so the app can stay signed in. |

The person sees these on the Allow screen the first time, and again when the app asks for more. Arizu's own apps skip that screen.

### Office access for control panels

Every Arizu control panel signs its admins in with `openid profile email office` and lets the office decide who gets in:

- The claim is worked out for the app that asks, when the token is made. An office admin counts when their admin account is linked to this Arizu account, or, if it is not linked to any account, when its email equals the account's email (compared by blind index). Only active admins count.
- A Super Admin gets `{"admin": true, "level": 3, "group": "Super Admin", "super": true}` for every app. Another office admin gets the level set for this app on their page under Admins › App access, and level 0 when nothing is set. Someone who is not an active office admin gets `{"admin": false, "level": 0, "group": null, "super": false}`.
- `level` 0 means no access. Refuse the sign-in with plain text and end that person's sessions in the panel.
- Map the level to the panel's own groups: 3 to Super Admin, 2 to a group that can change things, 1 to a read-only group. Create or update the panel's admin row on every sign-in, so the panel never needs a setup form or an invitation.
- A change in the office reaches the panel at that person's next sign-in.

When `picture` is missing, show the first letter of `name` on a color of your choice.

## The sign-in flow

1. Make a `code_verifier`: 43 to 128 random characters from `A-Z a-z 0-9 - . _ ~`. The `code_challenge` is the base64url of its SHA-256, without padding.
2. Make a random `state`, and a random `nonce` if you check the ID token. Keep all three in the user's session.
3. Send the browser to the authorization address:

```
https://arizu.id/account/oauth/authorize?response_type=code
  &client_id=arz_0123456789abcdef01234567
  &redirect_uri=https%3A%2F%2Fapp.example%2Fauth%2Farizu
  &scope=openid%20profile%20email
  &state=Rk9p3x...
  &nonce=Qz81Lm...
  &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
  &code_challenge_method=S256
```

| Parameter | Required | Notes |
|---|---|---|
| `response_type` | yes | Always `code`. |
| `client_id` | yes | From the office. |
| `redirect_uri` | yes | One of the registered addresses, exactly. |
| `scope` | yes | Space-separated, must include `openid`. |
| `code_challenge` | yes | 43 characters, see step 1. |
| `code_challenge_method` | yes | Always `S256`. |
| `state` | recommended | Returned unchanged. Check it. |
| `nonce` | recommended | Copied into the ID token. Check it. |
| `prompt` | no | `none` (never show a page; fail with `login_required` or `consent_required`), `login` or `select_account` (sign in with Google again), `consent` (show the Allow screen again). |
| `max_age` | no | Seconds since the last Google sign-in before Arizu asks again. |

4. Arizu signs the person in with Google if needed, shows the Allow screen if needed, then sends the browser back:

```
https://app.example/auth/arizu?code=ac_...&state=Rk9p3x...&iss=https://arizu.id
```

5. Check that `state` matches and `iss` is `https://arizu.id`. Then trade the code within 5 minutes:

```
curl -X POST https://arizu.id/account/oauth/token \
  -u "arz_0123456789abcdef01234567:arzs_your_client_secret" \
  -d grant_type=authorization_code \
  -d code=ac_... \
  -d redirect_uri=https://app.example/auth/arizu \
  -d code_verifier=the_verifier_from_step_1
```

Public apps send `client_id` in the body instead of `-u`, with no secret.

```
{
  "access_token": "at_...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "scope": "openid profile email",
  "id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ii4uLiJ9..."
}
```

6. Check the ID token before you trust it: the signature (RS256, key from the JWKS by `kid`), `iss` is `https://arizu.id`, `aud` is your `client_id`, `exp` is in the future and `nonce` matches. Then sign the person in with `sub`.

Sample ID token claims:

```
{
  "iss": "https://arizu.id",
  "aud": "arz_0123456789abcdef01234567",
  "azp": "arz_0123456789abcdef01234567",
  "sub": "5f0c2a9e41b7d3c86a12",
  "iat": 1794470400,
  "exp": 1794474000,
  "auth_time": 1794470380,
  "nonce": "Qz81Lm...",
  "at_hash": "q2Jr...",
  "name": "Rina Wijaya",
  "picture": "https://arizu.id/media/account/u4c1f0e9b2a7d3c86a12bb0de.jpg",
  "updated_at": 1794470300,
  "email": "rina@example.com",
  "email_verified": true
}
```

## A server app in PHP

The whole flow with no library: two routes, one to start and one to come back to.

```
session_start();
const CLIENT_ID = 'arz_0123456789abcdef01234567';
const SECRET = 'arzs_your_client_secret';
const BACK = 'https://app.example/auth/arizu';
const BASE = 'https://arizu.id/account';
function b64u(string $s): string { return rtrim(strtr(base64_encode($s), '+/', '-_'), '='); }
if ($_SERVER['REQUEST_URI'] === '/login') {
    $_SESSION['pkce'] = b64u(random_bytes(32));
    $_SESSION['state'] = b64u(random_bytes(16));
    $_SESSION['nonce'] = b64u(random_bytes(16));
    header('Location: ' . BASE . '/oauth/authorize?' . http_build_query([
        'response_type' => 'code', 'client_id' => CLIENT_ID, 'redirect_uri' => BACK,
        'scope' => 'openid profile email', 'state' => $_SESSION['state'], 'nonce' => $_SESSION['nonce'],
        'code_challenge' => b64u(hash('sha256', $_SESSION['pkce'], true)), 'code_challenge_method' => 'S256',
    ], '', '&', PHP_QUERY_RFC3986));
    exit;
}
if (!hash_equals($_SESSION['state'] ?? '', $_GET['state'] ?? '') || isset($_GET['error'])) {
    exit('Sign-in failed or was cancelled.');
}
$ch = curl_init(BASE . '/oauth/token');
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_USERPWD => CLIENT_ID . ':' . SECRET, CURLOPT_POSTFIELDS => http_build_query([
    'grant_type' => 'authorization_code', 'code' => $_GET['code'], 'redirect_uri' => BACK, 'code_verifier' => $_SESSION['pkce'],
])]);
$t = json_decode(curl_exec($ch), true);
[$h, $p, $sig] = explode('.', $t['id_token']);
$claims = json_decode(base64_decode(strtr($p, '-_', '+/')), true);
if ($claims['iss'] !== 'https://arizu.id' || $claims['aud'] !== CLIENT_ID || $claims['exp'] < time() || !hash_equals($_SESSION['nonce'], $claims['nonce'] ?? '')) {
    exit('The ID token did not check out.');
}
$_SESSION['user'] = ['arizu_id' => $claims['sub'], 'name' => $claims['name'] ?? '', 'email' => $claims['email'] ?? ''];
```

The token came straight from Arizu over HTTPS with your secret, so the claim checks above are enough here. Apps that receive ID tokens from anywhere else must also check the signature against the JWKS.

## Phones and desktop apps

- Open the authorization address in the system browser: Custom Tabs on Android, `ASWebAuthenticationSession` on iOS, the default browser on desktop. Never use a WebView, because Google refuses sign-in inside WebViews.
- Use an app scheme in reverse domain form as the return address, such as `id.arizu.flipbonk:/oauth`, or an https App Link. Desktop apps may use `http://127.0.0.1:<any port>/callback`; register it once with any port.
- Send no secret. PKCE proves the app.
- Libraries that work: AppAuth for Android and iOS, `flutter_appauth` for Flutter, `oidc-client-ts` for browser apps.

## Staying signed in

Ask for `offline_access` to get a `refresh_token` (30 days). Trade it for new tokens before the access token expires:

```
curl -X POST https://arizu.id/account/oauth/token \
  -u "arz_0123456789abcdef01234567:arzs_your_client_secret" \
  -d grant_type=refresh_token \
  -d refresh_token=rt_...
```

Every refresh returns a new refresh token, and the old one stops working. If an old refresh token is used again, Arizu treats it as stolen and revokes every token from that sign-in, so always store the newest one.

Refreshing fails with `invalid_grant` when the person removed your app from their account, deleted the account, or was suspended. Sign them out then.

## User info

```
curl https://arizu.id/account/oauth/userinfo -H "Authorization: Bearer at_..."
```

It returns the same claims as the ID token, for the scopes of that token, and answers `401` with `invalid_token` when the token expired or was revoked.

## Signing out

Sign the person out of your app first. To also sign them out of Arizu on that browser, send them to:

```
https://arizu.id/account/oauth/logout?client_id=arz_0123456789abcdef01234567
  &post_logout_redirect_uri=https%3A%2F%2Fapp.example%2Fbye
  &state=abc
```

You can send `id_token_hint` instead of `client_id`. Arizu asks the person to confirm, then returns to `post_logout_redirect_uri` if it is one of the app's registered sign-out addresses.

To end the app's own access, revoke the refresh token:

```
curl -X POST https://arizu.id/account/oauth/revoke -u "arz_...:arzs_..." -d token=rt_...
```

## Errors

Errors on the way back to your app arrive as `error` and `error_description` next to `state`:

| `error` | Meaning |
|---|---|
| `access_denied` | The person tapped Cancel. |
| `login_required` | `prompt=none`, and nobody is signed in. |
| `consent_required` | `prompt=none`, and the person has not allowed the app yet. |
| `invalid_scope` | A scope is unknown, not allowed for the app, or `openid` is missing. |
| `invalid_request` | PKCE is missing or not `S256`. |
| `unsupported_response_type` | `response_type` is not `code`. |

A wrong `client_id` or `redirect_uri` never goes back to the app: Arizu shows an error page instead.

The token endpoint answers JSON with `error` and `error_description`: `invalid_client` (401, wrong or missing secret), `invalid_grant` (code or refresh token expired, used or not yours, or the verifier does not match), `invalid_scope`, `unsupported_grant_type`, and `slow_down` (429).

## Limits and security

- Codes last 5 minutes and work once. Using a code twice revokes every token made from it.
- Access tokens and ID tokens last 1 hour. Refresh tokens last 30 days and rotate.
- The token endpoint takes 120 requests a minute from one IP address.
- Return addresses match exactly. Only public apps on `127.0.0.1` may change the port.
- Signing keys can change. Read the JWKS by `kid` and cache it for at most a day.
- Turning an app off in the office refuses new sign-ins and revokes its tokens.
