Repository navigation
Mobile auth app setup
This guide shows how a Pair v4 application can enable the built-in mobile authentication contract used by PairMobileKit and PairMobileAndroid.
Apply the framework migration that creates api_tokens:
php migrate.php
or apply the file explicitly in projects that run migrations manually:
migrations/20260510_api_tokens.sql
migrations/20260510_api_tokens_device_metadata.sql
The table stores only token hashes. Raw access and refresh tokens are returned once, in login, registration, or refresh responses.
Use short-lived access tokens and longer refresh tokens:
PAIR_MOBILE_ACCESS_TOKEN_LIFETIME=900
PAIR_MOBILE_REFRESH_TOKEN_LIFETIME=2592000
Invalid or non-positive values fall back to the framework defaults above.
Applications that extend Pair\Api\ApiController get these routes through authAction():
POST /api/auth/login
POST /api/auth/register
POST /api/auth/refresh
GET /api/auth/me
POST /api/auth/logout
POST /api/auth/passkey/options
POST /api/auth/passkey/verify
GET /api/auth/passkeys
POST /api/auth/passkeys/options
POST /api/auth/passkeys/verify
DELETE /api/auth/passkeys/{id}
The same contract works under versioned API prefixes such as /api/v1 when the application router maps the API module there.
The runtime also accepts DELETE /api/auth/logout; the OpenAPI helper publishes POST as the standard documented operation.
login, refresh, me, and logout are usable without app code. Registration is intentionally app-owned because products differ on required fields, privacy consent, tenant bootstrap, and welcome flows.
<?php
namespace App\Modules\Api;
use App\Models\User;
use Pair\Api\ApiController as BaseApiController;
use Pair\Api\ApiErrorResponse;
class ApiController extends BaseApiController {
/**
* Return the user snapshot exposed to native clients.
*/
protected function mobileAuthUserSnapshot(\Pair\Models\User $user): array {
return [
'id' => (int)$user->id,
'email' => $user->email,
'name' => $user->fullName(),
];
}
/**
* Return optional application context restored at startup.
*/
protected function mobileAuthContext(\Pair\Models\User $user): ?array {
return [
'tenant' => 'default',
];
}
/**
* Validate signup input and create the application user.
*/
protected function mobileAuthRegisterUser(array $body): \Pair\Models\User|ApiErrorResponse {
if (empty($body['email']) or empty($body['password']) or empty($body['privacy_accepted'])) {
return $this->errorResponse('BAD_REQUEST');
}
$user = new User();
$user->email = trim((string)$body['email']);
$user->username = $user->email;
$user->name = trim((string)($body['name'] ?? ''));
$user->hash = User::getHashedPasswordWithSalt((string)$body['password']);
$user->enabled = true;
$user->store();
return $user;
}
}
Adapt the example to the application's actual user fields, tenant ownership, validation rules, and consent records.
Use SpecGenerator::addMobileAuthPaths() when generating the application OpenAPI document:
use Pair\Api\OpenApi\SpecGenerator;
$spec = new SpecGenerator('Example API', '1.0.0');
$spec->addMobileAuthPaths('/api/v1');
return $spec->toJson();
The helper adds the standard auth paths, component schemas, and bearerAuth security scheme.
Both native libraries expect:
access_token- optional
refresh_token -
expires_inorexpires_at user- optional
context
Startup must run through the platform session manager before internal screens are shown. Network failures should keep the local snapshot; definitive auth failures should clear it.
Pair does not expose generic admin revocation endpoints in the core API because admin ACL, tenant scope, support impersonation, and audit policy are application-specific.
Recommended application endpoints:
GET /api/admin/users/{userId}/tokens
DELETE /api/admin/users/{userId}/tokens/{tokenId}
DELETE /api/admin/users/{userId}/tokens
Implementation rules:
- require an explicit admin permission before reading or mutating token rows
- resolve
userIdinside the application's tenant or ownership scope - never return raw token hashes
- show only safe metadata such as token ID, device name, created time, last used time, expiration, and revocation state
- use
ApiToken::revokeByIdForUser()for device/session revocation - use
ApiToken::revokeAllForUserAndDevice()when the app records a stable device hash and needs to revoke all bearer tokens for one device - use
ApiToken::revokeAllForUser()for account-wide mobile logout - write an audit record when support or admin users revoke another user's tokens
This keeps the generic token model reusable while leaving sensitive authorization policy in the application.
Apply migrations/20260918_user_passkeys.sql, then configure the relying party and every trusted web or signed Android origin:
PASSKEY_RP_ID=example.test
PASSKEY_RP_NAME="Example App"
PASSKEY_ALLOWED_ORIGINS="https://example.test,android:apk-key-hash:BASE64URL_SHA256_CERTIFICATE"
PASSKEY_REQUIRE_USER_VERIFICATION=true
The mobile endpoints always request and enforce user verification, use discoverable credentials for username-free login, keep challenges in short-lived cookie-free flow sessions, and issue the same api_tokens Bearer session used by password login. Registration accepts browser-extracted public keys as well as native iOS and Android CBOR attestation objects.
Only POST /auth/passkey/options and POST /auth/passkey/verify are public. Listing, registration, and revocation under /auth/passkeys* require a valid Bearer token and return 401 when it is missing. Revocation is owner-scoped, exposes a foreign identifier as not found, and remains idempotent when the owned credential is already revoked.
For iOS, add webcredentials:example.test to Associated Domains and publish an AASA file containing the app identifier. For Android, publish /.well-known/assetlinks.json with the production package and signing-certificate fingerprint. A simulator, debug signature, or local unit test does not prove either signed association chain.
See also: ApiController, ApiToken, Mobile iOS stack, Mobile Android stack, API.
Maintained by Viames Marino — VM Ingegneria · Professional enquiries
Home · Setup · Configuration
Build with Pair 4
- Generator
- Controllers and responses
- Read models
- ActiveRecord and queries
- Forms and validation
- PairUI.js, PairMotion.js and HTML fragments
APIs and authentication
- API guide and CRUD
- Middleware and rate limits
- Users, sessions, and ACL
- Passkeys and social login
- Native mobile setup
Integrate and operate
- Integrations
- Runtime extensions and adapter keys
- Cache and cache stores
- Logs and observability
- PWA and push
- Packages and distribution
- Upgrade to v4