Native app sign-in
Sign users in from iOS, Android, and Flutter apps with Sign in with Apple and Google Sign-In ID tokens, and keep them signed in with rotating token pairs.
Native app sign-in
Mobile apps sign in with the platform SDKs, such as sign_in_with_apple and google_sign_in in Flutter, or AuthenticationServices and Google Sign-In on iOS. The SDK hands your app an ID token. Your app sends it to Ploy Auth, which verifies it and returns a token pair: a short-lived access token and a refresh token that rotates on every use. No browser redirect and no cookie are involved.
Ploy checks every ID token before it signs anyone in:
- The RS256 signature is checked against the provider's published keys.
- The issuer must match exactly, and the audience must be one of your configured client IDs. For Google, the authorized party (
azp) must be one of your app client IDs. - The token must not be expired. 60 seconds of clock skew are tolerated.
- The nonce must match when the app sends one.
- Apple tokens, and Google tokens sent with a nonce, must have been issued within the last 10 minutes, and each signs in only once. See Nonces and token reuse for Google tokens without a nonce.
Configure the providers
Open Auth → Settings in the dashboard. Under Google or Apple, the Native app sign-in section holds the settings below. You can also set them with ploy api auth update --provider <google|apple>.
Apple
| Field | Value |
|---|---|
| Services ID | Your web Services ID, as for web sign-in |
| App bundle IDs | Your app's bundle ID, e.g. com.example.app. Native ID tokens are issued to the bundle ID. |
| Team ID, Key ID and key | As for web sign-in. Ploy uses the key to exchange the authorization code and to revoke tokens. |
| Require a nonce | Recommended. Refuses tokens without a nonce. |
ploy api auth update my-app --org <org-id> --provider apple \
--audience com.example.app --require-nonce| Field | Value |
|---|---|
| Client ID | Your Web application client ID. Pass it to the SDK as serverClientId, so ID tokens are issued to it. |
| Additional client IDs | Other client IDs that tokens may be issued to, if any. |
| Authorized parties (azp) | Your iOS and Android client IDs. When set, only tokens that your apps requested are accepted. |
| Require a nonce | Recommended once every app version sends a nonce. See Nonces and token reuse. |
ploy api auth update my-app --org <org-id> --provider google \
--authorized-party 1234-ios.apps.googleusercontent.com \
--authorized-party 1234-android.apps.googleusercontent.comNonces and token reuse
Google's SDKs hand back a cached ID token for up to its one-hour lifetime, for example when a user signs out and in again. So that this keeps working for apps that send no nonce, a Google token sent without a nonce is only checked for expiry. It may sign in more than once within its lifetime, and a nonce that the SDK added on its own is not checked.
A Google token sent with a nonce, and every Apple token, must be at most 10 minutes old and signs in only once. Turn on Require a nonce once every app version you support sends one. Then a leaked Google ID token can no longer be used to sign in while it is still valid.
Native access token lifetime
Auth → Settings → Sign-ups and sessions → Native access token lifetime sets how long an access token is valid, from 5 minutes to 1 day. The default is 1 hour. The refresh token follows the session lifetime and maximum age: it expires after the session lifetime without use, and never later than the maximum session age after sign-in.
Sign in
Send the ID token to your server, which calls the PLOY_AUTH binding. Pass the IP of the app's request so rate limits apply per user:
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (url.pathname === "/api/sign-in/apple" && request.method === "POST") {
const { idToken, nonce, authorizationCode, name } = await request.json();
const { user, newUser, session } = await env.PLOY_AUTH.signInWithIdToken(
{ provider: "apple", idToken, nonce, authorizationCode, name },
{ ip: request.headers.get("X-Forwarded-For")?.split(",")[0] },
);
return Response.json({ user, newUser, session });
}
return new Response("Not found", { status: 404 });
},
} satisfies Ploy;The app can also post the same JSON straight to Ploy Auth without your server in between:
POST /_ploy/auth/oauth/apple/id-token
Content-Type: application/json
{ "idToken": "eyJ…", "nonce": "raw-nonce", "authorizationCode": "c1d…", "name": "Ada Lovelace" }Both return:
{
"user": {
"id": "…",
"email": "…",
"emailVerified": true,
"metadata": { "name": "Ada Lovelace" }
},
"newUser": true,
"session": {
"accessToken": "eyJ…",
"accessExpiresAt": "2026-01-01T13:00:00.000Z",
"refreshToken": "ploy_rt_…",
"refreshExpiresAt": "2026-01-08T12:00:00.000Z"
}
}| Field | Description |
|---|---|
idToken | The ID token from the SDK. |
nonce | The raw nonce your app generated. With Apple, pass its SHA-256 hex digest to the SDK and the raw value here. With Google, either form works. |
authorizationCode | Apple only. Ploy exchanges it for the refresh token it needs to revoke the user's consent. Sign-in still works if the exchange fails. |
name | Apple only. The name Apple returns with the first credential. Apple does not sign it, so Ploy only uses it to name a new account, capped at 100 characters. |
link | { "sessionToken": "…" } links the provider account to a signed-in user instead. See Link an account. |
Which account signs in
- A provider account that signed in before signs in to the same user.
- Otherwise, a verified email address that matches an existing user signs in to that user. Apple addresses count as verified, including private relay addresses. Google addresses count only for
gmail.comand Google Workspace accounts. For other Google addresses, Google is not the authority, so the request fails withaccount_existsinstead. - Otherwise a new user is created when sign-ups are allowed. A Google address that Google marked as verified creates a verified account.
Use the access token
Send the access token as Authorization: Bearer <accessToken> to your server, and check it with env.PLOY_AUTH.getUser(token). The access token is a JWT, so apps can read its exp claim to schedule a refresh. Every check also looks up the session, so a revoked session stops working immediately.
Refresh the session
Refresh shortly before accessExpiresAt:
const session = await env.PLOY_AUTH.refreshSession(refreshToken, { ip });POST /_ploy/auth/token
Content-Type: application/json
{ "grant_type": "refresh_token", "refresh_token": "ploy_rt_…" }The response is a new pair, { "session": { … } } over HTTP. The old refresh token and the old access token stop working.
Store only the latest refresh token, and never refresh twice at the same time. A refresh token used again more than 10 seconds after its first use is treated as stolen: Ploy signs out the whole session. A retry within 10 seconds, for example after a lost response, gets the same new pair.
A failed refresh answers 401 with invalid_grant or refresh_token_reused. Sign the user in again.
Sign out
Send the refresh token. It ends the session even after the access token expired:
await env.PLOY_AUTH.revokeSession(refreshToken);POST /_ploy/auth/token/revoke
Content-Type: application/json
{ "token": "ploy_rt_…" }Unknown tokens are ignored, so signing out always succeeds.
Token pairs for other sign-in methods
Server code can start a token session for a user it has authenticated in another way:
const { user, session } = await env.PLOY_AUTH.issueSession(userId, { ip });issueSession runs the beforeSignIn hook with method server. Browsers cannot call it.
Apps can also sign in with a password or an email code and get a token pair. To do that, add "transport": "token" to POST /_ploy/auth/signin or POST /_ploy/auth/email-code/verify. The response then carries a session next to user, and Ploy sets no cookie. Requests from web pages, which send an Origin header, keep using the cookie.
Link an account
To add Apple or Google to a signed-in user, send their session token with the ID token:
{
"idToken": "eyJ…",
"nonce": "…",
"link": { "sessionToken": "<access token>" }
}The session must have signed in within the last 10 minutes, otherwise the request fails with reauth_required. A provider account that already belongs to another user fails with identity_in_use. Without link, Ploy never links a provider account to a session.
Delete an account
Apple requires apps that offer Sign in with Apple to revoke the user's tokens when they delete their account:
const { revokedProviders } = await env.PLOY_AUTH.deleteUser(userId, {
revokeProviderTokens: true,
});This revokes the user's Apple and Google grants, then deletes the user with their sessions, provider accounts and passkeys. A failed revocation does not stop the deletion. GET /_ploy/auth/identities returns hasProviderRefreshToken for each provider account. When it is false for Apple, ask the user to sign in with Apple again so that Ploy receives a new authorization code.
Apple server-to-server notifications
In the Apple Developer portal, set the server-to-server notification endpoint of your App ID to:
https://<your-domain>/_ploy/auth/apple/notificationsPloy verifies each notification against Apple's signing keys and handles each delivery once. An event from before the user last signed in with Apple is ignored, so a delayed delivery cannot undo a newer sign-in. Ploy handles these events:
| Event | What Ploy does |
|---|---|
consent-revoked, account-delete | Signs out all of the user's sessions, removes the Apple account link, and runs the afterIdentityRevoked hook. |
email-disabled, email-enabled | Updates whether the private relay address of the Apple account accepts mail. |
Errors
| Status | Code | Meaning |
|---|---|---|
| 401 | invalid_id_token | The signature, issuer or issue time is invalid. |
| 401 | invalid_audience | The token was issued for a client ID that is not configured. |
| 401 | id_token_expired | The token expired, or it must be fresh and is older than 10 minutes. |
| 401 | nonce_mismatch | The nonce does not match, or only one side has one. |
| 401 | nonce_required | Require a nonce is on and no nonce was sent. |
| 401 | id_token_replayed | This single-use ID token was already used. Get a new one from the SDK. |
| 403 | reauth_required | Linking needs a session that signed in within the last 10 minutes. |
| 409 | account_exists | The email address belongs to an account the token may not sign in to. |
| 409 | identity_in_use | The provider account is linked to another user. |
| 429 | rate_limited | Too many attempts from this IP address or for this provider account. |
| 503 | provider_unavailable | The provider's signing keys could not be loaded. Retry later. |
The binding throws an error with the same status and code properties.
Test locally
The local emulator reads the provider settings from your .env:
PLOY_AUTH_GOOGLE_CLIENT_ID=1234-web.apps.googleusercontent.com
PLOY_AUTH_GOOGLE_CLIENT_SECRET=...
PLOY_AUTH_GOOGLE_AUTHORIZED_PARTIES=1234-ios.apps.googleusercontent.com
PLOY_AUTH_APPLE_AUDIENCES=com.example.app
PLOY_AUTH_ACCESS_TOKEN_TTL=300In tests, PLOY_AUTH_GOOGLE_JWKS_URL and PLOY_AUTH_APPLE_JWKS_URL point the emulator at your own signing keys, so you can sign test ID tokens yourself.
How is this guide?
Last updated on