# Authorization Flow

Connect is a standard OAuth 2.0 authorization code flow with PKCE (RFC
7636). For OAuth itself, see [oauth.net/2](https://oauth.net/2/). This page
walks through the flow step by step.

## What's different about PCA's OAuth

- The user sees the consent screen on every authorization, and there is
  no `prompt=none`.
- PKCE is required, with S256 only.
- A redirect URI matches exactly, except that a loopback one (`127.0.0.1`
  or `[::1]`, never `localhost`) may use any port.
- Refresh tokens rotate, with a 30-second grace and a theft rule: see
  [Tokens](/documentation/developers/tokens/#refresh-tokens-rotate).
- A sign-in made with a secret refreshes and revokes only with that secret.
- One sign-in per device, up to 10 per app.
- `resource`, if you send it, must equal the issuer.
- Revocation follows RFC 7009: it answers `200` for any token.

## 1. Discover the endpoints

Read the OAuth endpoints from the [authorization server
metadata](https://api.precisioncutarchery.com/.well-known/oauth-authorization-server)
(RFC 8414), not the OpenAPI document, and don't hardcode them. They
follow OAuth's conventions (form bodies, RFC 6749 errors) rather than the
API's.

```
GET https://api.precisioncutarchery.com/.well-known/oauth-authorization-server
```

If your OAuth library supports RFC 8414 discovery, point it there. The
API's protected resource metadata (RFC 9728), which a `401`'s
`WWW-Authenticate` challenge names, is at
`https://api.precisioncutarchery.com/.well-known/oauth-protected-resource`.

Connect isn't OpenID Connect: there's no ID token, no userinfo endpoint and
no `/.well-known/openid-configuration`. If your library asks for a userinfo
endpoint, use `pca_subject` from the [token
response](#5-exchange-the-code-for-tokens) instead.

## 2. Send the user to us to authorize

Redirect the user's browser (or open a system browser view, for mobile) to
the authorization endpoint with these query parameters:

| Parameter | Value |
|---|---|
| `response_type` | `code` |
| `client_id` | your registered client ID |
| `redirect_uri` | one of your registered redirect URIs, matched **exactly** (a loopback redirect may use any port; [never `localhost`](/documentation/developers/getting-access/#testing-locally)) |
| `scope` | space-separated scopes, e.g. `compute:build compute:analyze compute:air` |
| `state` | an opaque value you generate, at most 1024 characters. Always send it: it's how your callback knows the redirect belongs to the attempt it started (step 4) |
| `code_challenge` | the S256 PKCE challenge |
| `code_challenge_method` | `S256` (`plain` is refused) |
| `resource` | optional (RFC 8707); if you send it, it must equal the issuer, `https://api.precisioncutarchery.com` |

Generate a fresh `code_verifier` for every attempt and keep it in memory
for that attempt only. The
[Quickstart](/documentation/developers/quickstart/#2-generate-a-pkce-pair)
shows how to compute the challenge.

If `client_id` or `redirect_uri` doesn't match, we show our own error page
instead of redirecting. That page says only that the connection didn't work;
the reason is in the API's own response. For an app in development, check
that the `redirect_uri` is registered exactly as you send it, and that a
loopback URI uses `127.0.0.1` or `[::1]`, not `localhost`. Every other
rejection redirects back to your `redirect_uri` with an `error`.
[Errors](/documentation/developers/errors/#the-authorize-endpoint-get-oauthauthorize)
lists them.

## 3. The user signs in and consents

We show our own sign-in page, then a consent screen naming your app and
the scopes it asks for. The user sees it each time your app sends them to
connect, on each device, and each approval starts its own sign-in. Between
authorizations, your app keeps the sign-in alive with [refresh
tokens](/documentation/developers/tokens/).

Some users don't come back with a code: those with no Precision Cut Archery
account, no active subscription, or (for an app in development) who aren't
a test account. We send them to sign up or renew, or offer a way back to
your app, which returns `access_denied`. A request left unanswered expires
after an hour.

## 4. Handle the callback

We redirect back to your `redirect_uri` with either a code or an error:

```
GET https://your-app.example/callback?code=...&state=...&iss=https://api.precisioncutarchery.com
GET https://your-app.example/callback?error=access_denied&error_description=...&state=...&iss=https://api.precisioncutarchery.com
```

Before anything else:

1. **Check `state`** matches the value you sent for this attempt. If not,
   refuse the request.
2. **Check `iss`**, on an error redirect too, equals
   `https://api.precisioncutarchery.com` (RFC 9207).

Only once both checks pass should you use the `code`.

If the redirect carries `access_denied`, or the user comes back to your
app with no redirect at all (they went to sign up, renew, or gave up), show
your app as not connected, with a "Connect Precision Cut Archery" action
that starts a new authorization with a new `state` and PKCE pair. Neither
is an error.

## 5. Exchange the code for tokens

`POST` to the token endpoint, form-encoded (`application/x-www-form-urlencoded`):

```
grant_type=authorization_code
code=<the code from the callback>
redirect_uri=<the same redirect_uri you sent to /oauth/authorize>
code_verifier=<the verifier matching your code_challenge>
client_id=<your client ID>            (when you send no secret, or client_secret_post)
resource=https://api.precisioncutarchery.com   (optional: the same if left out)
```

An app with a secret sends it as `client_secret_basic` or
`client_secret_post`, never both; see
[Secrets](/documentation/developers/getting-access/#secrets). A code issued
to a **backend** redirect URI is exchanged only with the secret.

The response is described in [Tokens](/documentation/developers/tokens/#the-token-response).

`scope` is what this sign-in's tokens can do: the scopes the user approved
that your app may still use. Read it rather than assuming what you asked
for.

`pca_subject` identifies the user to your app. It's the same on every
sign-in, on every device, and after the user disconnects and connects
again, but a different app sees a different value for the same person.
That's why your platforms share [one
registration](/documentation/developers/getting-access/#one-registration-per-product).
It is never our internal user ID or the user's email.
[Tokens](/documentation/developers/tokens/#formats) gives its format.

The code is single-use and lives 60 seconds. An exchange refused for a
wrong `redirect_uri`, `code_verifier`, client or `resource` leaves the code
usable for a corrected retry within that time. A code presented again after
it was exchanged gets `invalid_grant` and ends nothing, because a stolen
code is useless without its verifier. See
[Tokens](/documentation/developers/tokens/) for what the tokens are good
for.

## Mobile and desktop apps

Don't embed a login `WebView`. Use the system browser tab:
`ASWebAuthenticationSession` on iOS, Chrome Custom Tabs on Android.
Register a redirect URI your app can claim: an app-claimed HTTPS link, or
a private-use reverse-domain scheme such as
`com.yourcompany.yourapp:/callback`. A desktop app registers a loopback
redirect instead ([Testing
locally](/documentation/developers/getting-access/#testing-locally)).

On iOS, we recommend `prefersEphemeralWebBrowserSession`. The sign-in then
shares no cookies with Safari and iOS skips its prompt, at the cost that
the user signs in to Precision Cut Archery each time your app sends them to
connect. [Tokens](/documentation/developers/tokens/#ios-and-android)
covers where to keep the tokens.

A user who leaves the sheet to sign up or renew doesn't come back with a
redirect: the sheet reports a cancel. Treat a cancel as "not connected" and
offer Connect again.

If you use [AppAuth](https://appauth.io/), two things it leaves to you:

- **Check `iss` yourself.** AppAuth doesn't check the callback's `iss`, so
  read it from the redirect URL and refuse a mismatch.
- **`pca_subject`** arrives in the token response's
  `additionalParameters`.

A sketch with AppAuth-iOS 1.x (check the names against your version).
AppAuth's `discoverConfiguration(forIssuer:)` looks for an OpenID Connect
discovery document, which we don't serve, so build the configuration from
our metadata's endpoints:

```swift
let config = OIDServiceConfiguration(
  authorizationEndpoint: metadata.authorizationEndpoint, // from our metadata document
  tokenEndpoint: metadata.tokenEndpoint)
let request = OIDAuthorizationRequest(
  configuration: config, clientId: clientID, scopes: ["compute:analyze"],
  redirectURL: URL(string: "com.example.yourapp:/callback")!,
  responseType: OIDResponseTypeCode, additionalParameters: nil)
let agent = OIDExternalUserAgentIOS(presenting: viewController, prefersEphemeralSession: true)!
flow = OIDAuthorizationService.present(request, externalUserAgent: agent) { response, error in
  // No response: Deny, a cancel, or an error. Show "not connected".
  guard let response, response.additionalParameters?["iss"] as? String == issuer else { return }
  OIDAuthorizationService.perform(response.tokenExchangeRequest()!) { tokens, error in
    let subject = tokens?.additionalParameters?["pca_subject"] as? String
    // Keep tokens?.refreshToken and tokens?.accessToken in the Keychain.
  }
}
```
