One account for the web app, the iOS app, and the CLI
Same Authdog users on the web, in Swift, and in a CLI that signs in with a device code.
Authdog Team

You have a web app, a Swift iOS app, and a CLI. You want one user directory and a sign-in that feels the same in all three. The CLI should not bind a port on 127.0.0.1 and wait for a browser callback.
Put all three clients on one Authdog environment. The web app and the iOS app use the hosted Account Portal. The CLI uses the device authorization grant (RFC 8628): it prints a short code, the user approves that code in a browser they already have, and the terminal polls until a token shows up.
One environment
An environment is the user store, the sign-in methods, and the signing keys. A person who registers on the web is the same user record the iOS app and the CLI will see, as long as all three talk to that environment.
Copy the environment's public key (pk_...). It is safe in the web app and in the iOS binary. It only selects the environment. The client secret on an OIDC client is a different value. That one stays out of the app and out of git.
A token from dev will not validate in production. Ship each stage against its own environment.
The web app
Send people to the hosted Account Portal. Authdog renders sign-up, sign-in, and MFA for the methods you enabled: password, magic link, passkeys, social login, enterprise SSO. You theme it per environment. You do not build those screens.
After sign-in, Authdog issues a signed JWT.
- On a first-party site covered by the session cookie domain, the browser stores it as
authdog-session(HttpOnly,SameSite=Lax,Securein production). Your server reads the cookie. - On a separate API origin, the client sends
Authorization: Bearer <token>.
A framework SDK does the cookie path for you. Pick the stack in the quickstarts and protect one route with the server gate. Presence of a cookie, or a JWT-shaped string in the page, is not authentication. The gate checks the session before the handler runs. See Backend requests.
If you are wiring the browser yourself, the JavaScript client sends the user to the portal and reads the token when they return:
import { createAuthdogClient } from "@authdog/javascript"
const authdog = createAuthdogClient({
publicKey: process.env.NEXT_PUBLIC_PK_AUTHDOG,
})
authdog.handleRedirectCallback()
authdog.signIn()handleRedirectCallback only checks that ?token= looks like a JWT. Your API still validates it. @authdog/javascript publishes from the web-sdk repository. Confirm the package is on npm before you depend on a registry install. Server-rendered apps should prefer the framework SDK and the HttpOnly cookie.
The iOS app
Authdog does not publish a Swift login SDK. The Swift package in the MCP SDK verifies a bearer token on an MCP server. It does not open a sign-in screen.
Use the same Account Portal. ASWebAuthenticationSession presents it in a system browser sheet, so passkeys, Sign in with Apple, and an existing browser session work. You do not embed a web view that can see the password.
The return URL has to be http or https and match a redirect the environment allows (the success redirect on a verified domain). A custom scheme such as myapp://callback fails that check. On iOS 17.4 and later, point the session at an HTTPS callback:
import AuthenticationServices
final class SignInCoordinator: NSObject, ASWebAuthenticationPresentationContextProviding {
private let anchor: ASPresentationAnchor
private var session: ASWebAuthenticationSession?
init(anchor: ASPresentationAnchor) {
self.anchor = anchor
}
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
anchor
}
func start() {
var components = URLComponents(string: "https://id.example/signin/ENVIRONMENT_ID")!
components.queryItems = [
URLQueryItem(name: "redirect_uri", value: "https://app.example.com/ios/callback")
]
let session = ASWebAuthenticationSession(
url: components.url!,
callback: .https(host: "app.example.com", path: "/ios/callback")
) { callbackURL, error in
guard let callbackURL, error == nil else { return }
let token = URLComponents(url: callbackURL, resolvingAgainstBaseURL: false)?
.queryItems?
.first { $0.name == "token" }?
.value
// Store token in the Keychain. Send Authorization: Bearer to your API.
}
session.presentationContextProvider = self
session.prefersEphemeralWebBrowserSession = false
self.session = session
session.start()
}
}Replace the identity host and ENVIRONMENT_ID with the environment you copied the public key from. prefersEphemeralWebBrowserSession = false keeps the system browser session so the next sign-in is quieter.
Read token from the callback only when that host sits outside the session cookie domain. If identity is on a vanity host of the same site (id.example.com and app.example.com), Authdog sets the cookie and leaves token off the URL. A native app cannot read that HttpOnly cookie. Use a callback host the environment allows and that cookie domain does not cover.
Store the token in the Keychain. Send it as Authorization: Bearer to your API. The app's copy of the string is a UX hint. The API check is the boundary.
If the iOS app offers any social login besides Apple, App Store review expects Sign in with Apple on the same environment. Turn the connector on once. The portal shows it to the web app and to iOS.
React Native and Expo can skip the session boilerplate. @authdog/react-native opens the portal and stores the token from the callback. See React Native / Expo. That sample registers a custom-scheme callback. The identity service still allows only http and https on the redirect check, so confirm the callback your build sends is one the environment accepts.
A second provider (Google on the web, Apple on the phone) stays a second identity until the user links it. Linking lives in the Account Portal and requires a verified email that matches the account. After that, both methods resolve to the same subject.
The CLI, without a local server
The device authorization grant is the CLI path. The terminal never listens on localhost.
- In Authentication → Clients, create a confidential client. Token endpoint auth is HTTP Basic (
client_secret_basic). - Grant types are space-separated. Keep the defaults and add the device grant:
authorization_code refresh_token urn:ietf:params:oauth:grant-type:device_code- Scopes need
openid. Addprofileandemailwhen the CLI should read them. A requested scope missing from the client returnsinvalid_scope. - The form still requires a redirect URI. The device grant does not send the browser there. Use the web app's HTTPS callback.
- Copy the client secret once. Put
CLIENT_IDandCLIENT_SECRETin the operator environment, not in the repo.
The secret names the application. It does not sign a person in. A user in that environment still has to approve the code. A binary you ship can be unpacked, so rotate the secret when you need to stop new device grants from that build.
Discovery lists device_authorization_endpoint on the environment issuer, {issuer}/device. Start the grant:
ISSUER="https://id.example/oidc/$ENVIRONMENT_ID"
curl -s -u "$CLIENT_ID:$CLIENT_SECRET" \
-d "scope=openid profile email" \
"$ISSUER/device"The response contains:
| Field | What you do with it |
|---|---|
device_code |
Secret for the poll. Shown once. Stored as a hash. Do not print it. |
user_code |
Eight characters, shown as ABCD-EFGH. This is what the user types. |
verification_uri |
{issuer}/device/verify |
verification_uri_complete |
Same URL with user_code filled in. Open this. |
expires_in |
600 seconds. |
interval |
5 seconds. Wait at least this long between polls. |
The user opens the verification URL on any phone or laptop, signs in if the page asks, and chooses Approve or Deny. The page links through /signin/{environmentId} when they do not already have a session in that environment.
Poll the token endpoint with the same client authentication:
curl -s -u "$CLIENT_ID:$CLIENT_SECRET" \
-d "grant_type=urn:ietf:params:oauth:grant-type:device_code" \
-d "device_code=$DEVICE_CODE" \
"$ISSUER/token"HTTP 400 is normal while you wait. Keep polling when error is authorization_pending. If you poll early, the response is slow_down: wait out the new interval, then continue. Stop on access_denied, expired_token, or invalid_grant.
A successful poll returns an access token for the user who approved the code. The sample scope leaves out offline_access, so the response has no refresh token. When the access token expires, run the device flow again. Store the access token in the OS credential store or in a file the user owns (0600). Do not write it to shell history.
The Authdog CLI wraps the same two calls:
ISSUER="https://id.example/oidc/$ENVIRONMENT_ID" \
CLIENT_ID="..." CLIENT_SECRET="..." \
authdog device authorize --pollYour product CLI can call the HTTP endpoints itself. It does not need a loopback listener to do it.
There is a separate browser handoff that can redeem a session through an optional localhost URL. That flow is documented in Browser-based CLI authentication. The device grant is the one that leaves the terminal offline.
One check on the API
Web, iOS, and CLI should hit the same backend check. Read authdog-session or Authorization: Bearer, then validate with the environment public key and the identity provider's userinfo endpoint. Userinfo checks the signature, expiry, and revocation, and returns the current profile.
import os
from fastapi import Depends, FastAPI
from authdog.fastapi import Authdog
app = FastAPI()
authdog = Authdog(public_key=os.environ["PK_AUTHDOG"])
@app.get("/me")
async def me(user=Depends(authdog.require_auth)):
return userA resolved user is not a permission grant. Enforce authorization on the server after the session check. Hiding a button in Swift, or branching on a claim in the CLI, is only a hint.
Limits
- The device code lives for 10 minutes. The user code uses an alphabet without
0,O,1,I, orL. - The device client is confidential. Public PKCE clients are a different registration. This grant expects HTTP Basic.
- The device flow in this article does not request
offline_access, so you get an access token and then an interactive approve when it ends. - The access token's lifetime is the client's access-token lifetime, not the 10-minute device code.
- Sign-out and revocation show up on the next userinfo check. Authdog does not push that into a process that is already holding a token and skipping validation.
- Users, connections, and keys are per environment. The iOS build, the website, and the CLI have to share one, or you will debug three directories.
Check it
- Sign up on the web app. Note the user id from
/me. - Sign in on the iOS app against the same environment.
/mereturns that id. The Keychain holds the bearer. The API rejects a mutated token. - Run the device grant from the CLI. Approve the code in a browser that is not the terminal.
/mewith that access token returns the same id. - Deny a second code. The poll stops with
access_denied. - Let a code sit for 10 minutes. The poll stops with
expired_token.
Related
| Read | To learn how to |
|---|---|
| Sign up and sign in | Enable methods and call the device endpoints |
| Account Portal | Use the hosted screens on web and iOS |
| Backend requests | Validate the cookie or bearer on your API |
| Sessions and tokens | See how the JWT is issued and revoked |
| React Native / Expo | Use the packaged mobile SDK |
| CLI | Run authdog device authorize |