Skip to main content
With Client Auth, Portal identifies your end user and creates their client for you. Your app starts a sign-in, Portal completes it, and PortalAuth hands you a PortalSession that you pass straight to Portal. No login system of your own, and no server-side call to mint a Client Session Token. The iOS SDK can complete a Google or Apple sign-in in two ways:
  • signInWithGoogle() / signInWithApple() present the provider in an ASWebAuthenticationSession sheet and return the result directly. Your app never opens a URL or handles a redirect. This is the recommended path.
  • loginWithGoogle() / loginWithApple() return an authorize URL for your app to open however it likes. The result arrives later as a deep link, which you read with parseRedirect(_:) and complete with completeOAuthLogin(_:).
Email magic links always arrive as a deep link, and they complete in two steps: your app shows the user the email address the link signs in to, and completes the sign-in only once they confirm it is theirs. See Confirm a magic link. Your app owns when a sign-in starts, all of its UI — including the screen that confirms a magic link — and forwarding redirects to the SDK. PortalAuth never touches wallets, MPC or signing, and never creates a Portal.
Client Auth requires PortalSwift 8.0.0 or later. From PortalSwift 8.2.0, Google and Apple sign-ins are bound to the device that started them; see Google and Apple sign-ins are bound to the device. Upgrade before Portal starts requiring this: Google and Apple sign-ins without a code verifier are deprecated, and earlier versions will then no longer complete them.

Prerequisites

Installation

There is nothing new to install. PortalAuth ships in PortalSwift alongside Portal, and it adds no dependency of its own: the sign-in sheet is AuthenticationServices and the session lives in the Keychain. Sessions are persisted for you in the Keychain, under the service PortalSwift.auth.session.<authEnvironmentId>. That is deliberately a separate namespace from the one holding MPC key shares, so ending a session can never touch a wallet. The item is stored with kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly and is never synchronizable, so it stays on this device and does not sync through iCloud Keychain. A Google or Apple sign-in in progress is kept the same way, under PortalSwift.auth.oauthVerifier.<authEnvironmentId>; it can be completed for 15 minutes.
Keychain items survive app deletion, so a reinstalled app can find the previous install’s session. See Restore the session on launch for how to start a fresh install from a clean slate.

Register your redirect

iOS only delivers a redirect to your app if you register its scheme. For a redirect URL of myapp://auth/callback, add the scheme to Info.plist:
signInWithGoogle() and signInWithApple() need this custom scheme as well: the sign-in sheet matches the callback against it. They do not accept an https:// redirect URL in this release.
The redirect carries a single-use grant that the SDK exchanges for the user’s session. A custom scheme is not exclusive on iOS — any installed app can register the same myapp:// scheme, and iOS does not arbitrate between them — so a redirect delivered through the OS URL handler can reach another app instead of yours.The reverse is true as well: any web page, message or app can open your redirect URL, with a grant someone else obtained for their own account. If your app completed it, your user would be signed in to that person’s account. That is why a magic link is completed only after the user confirms its email address (see Confirm a magic link), and why Google and Apple sign-ins are bound to the device that started them.
  • Google and Apple sign-ins are bound to the device that started them, so another app that receives the redirect cannot exchange its grant, and a Google or Apple grant someone else obtained cannot sign your user in. See Google and Apple sign-ins are bound to the device. signInWithGoogle() and signInWithApple() also never route the callback through the OS: the sign-in sheet receives it itself.
  • Magic links are not bound to a device, and they always arrive through the OS. Portal limits the damage with a link that expires 15 minutes after it is sent and a byte-exact allow list. For production, prefer a Universal Link on a domain you own (https://example.com/auth/callback), which iOS delivers only to the app your domain’s apple-app-site-association file names. It keeps other apps from receiving your redirects, but not a web page or message from opening one. A Universal Link helps loginWithGoogle() / loginWithApple() too: with a custom scheme, another app that takes the redirect cannot use its grant, but the user’s sign-in fails.
redirectUrl is fixed per PortalAuth instance. An app that wants both — a custom scheme for signInWith* and a Universal Link for magic links — builds two instances with the same Auth Environment ID, one per redirect URL, and allow-lists both. They share the persisted session and the Google or Apple sign-in in progress, and each one ignores the other’s redirects. Each instance remembers its own last grant, so on sign-out call clearPersistedSession() on both.
The redirect URL must be byte-identical in three places: your environment’s allow list in the dashboard, the redirectUrl you pass to PortalAuth, and the scheme (or Universal Link domain) your app registers. A mismatch between the first two fails the sign-in with a 401; a mismatch between the last two means the redirect silently never reaches your app. See Redirect URLs.

Create a PortalAuth

Create one long-lived PortalAuth and reuse it.
A blank authEnvironmentId or redirectUrl throws PortalAuthError.invalidArgument(name:). The initializer makes no network or Keychain call.
Build PortalAuth once and hold it for the life of your app — on your app delegate, in an object your SwiftUI App owns, or in a dependency container — rather than one per screen. confirmMagicLink(_:), completeOAuthLogin(_:) and signInWith* remember the grant they last exchanged, so a re-delivered redirect replays the result instead of failing. That memory lives on the instance, only while the app runs and that session is live. Sessions are keyed by authEnvironmentId, so two instances on the same environment share the persisted session anyway.
isAccountAbstracted is fixed when you construct PortalAuth, and it only takes effect on a user’s first sign-in. A returning user keeps the client they already have.

Check which methods are enabled

getMethods() reports what your environment allows, so you can render only the buttons that will work.
Methods a newer backend has added but this SDK version does not recognize are dropped from allowedAuthMethods rather than surfaced. autoCreateWallet is a signal for your app — nothing in the SDK or the API acts on it. See Create or reuse the wallet.
A two-factor requirement is not visible here. It only appears when a sign-in is completed, so every completion path must be ready for it.

Start a sign-in

Google or Apple in a sign-in sheet

signInWithGoogle() and signInWithApple() fetch a fresh authorize URL, present the provider in an ASWebAuthenticationSession sheet, and exchange the result, all in one call. Set the window to present from first.
signInWith* throws PortalAuthSignInError.unavailable when no presentation anchor is set (or its window has gone away), or when redirectUrl is not a custom scheme. Only one signInWith* call runs at a time on a PortalAuth instance. Both provider URLs share one single-use state, so a second attempt while the first is open throws signInInProgress rather than invalidating the first. Cancelling the calling Task before the sheet returns its result dismisses the sheet and throws closed, and nothing is exchanged. Once the result has arrived, the exchange runs to completion even if the task is cancelled, which is why the sample also checks the sign-out counter. The sheet’s sign-in is bound to the device like any Google or Apple sign-in. A loginWithGoogle() or loginWithApple() call made while the sheet is open replaces it, and the sheet then throws PortalAuthError.oauthFlowNotStarted without exchanging its grant. If the sign-in cannot be stored in the Keychain, signInWith* throws PortalAuthError.sessionStorageFailure and shows no sheet. Keep the task, as SignInSheet does, so a sign-out can close the sheet. clearPersistedSession() cancels the sign-in itself, so a callback that still arrives is refused with PortalAuthError.oauthFlowNotStarted, but it cannot close a sheet that is still open, which would stay on screen after the sign-out.
By default the sheet shares Safari’s cookies, so a returning user who is already signed in to Google or Apple needs one tap. The SDK cannot clear those cookies, so after a sign-out the next sign-in reuses the same account. To let the user pick a different account, set portalAuth.prefersEphemeralWebBrowserSession = true before calling signInWith*.
Portal delivers Sign in with Apple as a web flow, so the button that starts it is your own control: follow Apple’s Human Interface Guidelines for it. A user who picks Hide My Email becomes a distinct end user, with a distinct wallet, from the same person signing in with Google or a magic link. See How Apple handles email addresses.

Google or Apple in your own browser

loginWithGoogle() and loginWithApple() return an authorize URL. They do not open a browser and do not wait for the sign-in to finish — your app opens the URL, and the result arrives later as a deep link. Use this path when you want to own the browser, or when your redirect URL is a Universal Link.
Each call starts a new sign-in bound to this device and replaces any earlier one: on one PortalAuth instance, only the URL returned last can complete. It is stored in the Keychain before the URL is returned, so it still completes if iOS terminates your app while the browser is open; if it cannot be stored, the call throws PortalAuthError.sessionStorageFailure and returns no URL. Your app keeps no record of its own. See Google and Apple sign-ins are bound to the device.
Fetch a fresh authorize URL for every attempt, when the user taps. A single backend response shares one single-use state across both providers, so caching a URL — or starting a Google sign-in and then an Apple one from the same response — invalidates the other. Fetching both providers’ URLs ahead of time fails too: only the URL fetched last can complete, and the other’s redirect is refused with PortalRequestsError.unauthorized.
If you call clearPersistedSession() — on sign-out, in an onSessionInvalidated listener, or on a fresh install — wait for it to return before calling loginWith* or signInWith*. It cancels the Google or Apple sign-in in progress, so the redirect of a URL returned before it fails with PortalAuthError.oauthFlowNotStarted. Calling it after a URL has returned abandons that sign-in, so do that only on purpose, and never in your redirect handler before completeOAuthLogin(_:). portal.clearSession() does not cancel a sign-in.
If the sign-in does not complete — the user cancels, the provider rejects it, or it fails for any other reason — Portal redirects to your redirectUrl with an error in the URL (error=oauth_failed), which parseRedirect(_:) returns as .failed(error:). If you drive your own ASWebAuthenticationSession rather than the system browser, its completion handler receives the callback URL instead of your app’s URL handler. Read that URL with parseRedirect(_:) and complete the .oauth result with completeOAuthLogin(_:) yourself — or use signInWith*, which does exactly that. If the provider is not enabled for your environment, both paths throw PortalAuthError.authMethodUnavailable. That is not retryable — read getMethods().allowedAuthMethods and present the method as unavailable instead.
A provider that is enabled but incompletely configured behaves differently, and worse: it fails the whole call rather than omitting its own URL, so a half-configured Apple takes Google down with it even though getMethods() reports both as available. It arrives as PortalRequestsError.unauthorized, which the backend also returns for an invalid Auth Environment ID and for a redirectUrl that is not on the allow list. If both providers start failing at once, check the provider credentials in the dashboard before suspecting your code.

Google and Apple sign-ins are bound to the device

This binding requires PortalSwift 8.2.0 or later. Earlier versions don’t bind a sign-in to the device that started it, and will no longer complete Google or Apple sign-ins once Portal requires the code verifier.
Every loginWithGoogle(), loginWithApple(), signInWithGoogle() and signInWithApple() call binds the new sign-in to this device with PKCE. The SDK creates a one-time secret and stores it in the Keychain. It sends Portal only a hash of the secret when the sign-in starts, and the secret itself when completeOAuthLogin(_:) or the sign-in sheet completes the sign-in. Completing requires that secret, so a redirect can’t sign the user in on a device or in an app that didn’t start the sign-in. You don’t pass or store anything yourself, and your app can pass every .oauth redirect it receives to completeOAuthLogin(_:): one this device didn’t start signs nobody in. This changes how sign-ins behave:
  • Finish on the device that started it. The sign-in must complete in the same app, on the same device. A redirect that reaches another device or app can’t complete.
  • One sign-in at a time. Each auth environment has one Google or Apple sign-in in progress on a device, shared by every PortalAuth instance built with that Auth Environment ID. Starting a new one replaces it, and a redirect from the earlier attempt can no longer complete: only the sign-in whose verifier was stored last can. On one PortalAuth instance, that is the one started last; across instances, it is whichever stored its verifier last. (A second signInWith* call on the same instance while a sheet is open throws signInInProgress instead.) A magic link can still run alongside a Google or Apple sign-in.
  • Finish within 15 minutes. The SDK keeps a sign-in for 15 minutes, and a redirect that arrives later can’t complete. Portal’s 10-minute limit on the provider step can end it sooner; see Grants are single use.
  • It survives your app being terminated. A sign-in started with loginWithGoogle() or loginWithApple() still completes if iOS terminates your app while the browser is open.
  • Clearing the stored session cancels it. clearPersistedSession() on any instance also cancels the Google or Apple sign-in in progress, and an exchange completeOAuthLogin(_:) or signInWith* is already running on that same instance. portal.clearSession() does not. See End the session.
A Google or Apple redirect carrying a grant that doesn’t belong to the sign-in in progress on this device can’t complete, and fails in one of two ways (a redirect for the sign-in this instance just completed is replayed instead; see Handle a re-delivered redirect):
  • If this device has no Google or Apple sign-in in progress — none was started here, it already completed and is no longer remembered (an earlier launch, another PortalAuth instance, or after clearPersistedSession()), it is more than 15 minutes old, or it was cancelled — completeOAuthLogin(_:) throws PortalAuthError.oauthFlowNotStarted. Nothing is sent to Portal, unless clearPersistedSession() cancelled the exchange while it was already running.
  • If a different sign-in is in progress, for example because a newer one replaced it, Portal refuses the grant and completeOAuthLogin(_:) throws PortalRequestsError.unauthorized.
In either case, start a new sign-in. A redirect that carries an error instead of a grant is .failed(error:) from parseRedirect(_:); see Read the redirect. sendMagicLink(_:) returns once Portal has handed the email off for delivery. It tells you nothing about the eventual sign-in, which arrives as a deep link when the user opens the link. Your app then asks the user to confirm the email address before the link is exchanged — see Confirm a magic link.
The API only accepts a lowercase address, so the iOS SDK trims and lowercases it for you. A blank address throws PortalAuthError.invalidArgument(name:), and a PortalAuth built without magicLink throws PortalAuthError.magicLinkNotConfigured, both before any network call.
Every call sends a real email, and sends are rate limited to 10 per address per minute, which surfaces as PortalAuthError.rateLimited. Never retry automatically; make a resend an explicit user action.
PortalRequestsError.unauthorized from sendMagicLink(_:) is a configuration problem, not a user one: the redirectUrl is not on the allow list, the fromEmail does not belong to a sending domain enabled for this environment, or the templateId does not exist. See Email magic links.
The link expires 15 minutes after it is sent. Some email security scanners open links before the user does. If that uses up the link, it shows up as PortalAuthError.grantRejected from getMagicLinkDetails(_:), which is your cue to offer a new link.

Complete the sign-in

handleRedirect(_:) is deprecated in PortalSwift 8.2.0 and will be removed in the next major version. It completes a magic link in one step, without first showing the user the email address and waiting for them to confirm, which lets a user be signed in from a link they did not request. Use parseRedirect(_:) and the methods below instead; see Migrate from handleRedirect.
parseRedirect(_:), getMagicLinkDetails(_:), confirmMagicLink(_:) and completeOAuthLogin(_:) require PortalSwift 8.2.0 or later.
Magic links and loginWithGoogle() / loginWithApple() come back to your app as a redirect to your redirectUrl. (signInWith* receives its own callback and needs none of this.) Completing a redirect takes two steps: read it with parseRedirect(_:), then complete it with the method for its kind of sign-in.

Read the redirect

Forward every URL your app receives to the same function:
parseRedirect(_:) reads the URL locally and synchronously: it sends nothing to Portal, touches no storage, logs nothing and uses up no grant, so it is safe to call on every URL your app receives. It never throws.
parseRedirect(_:) returns nil when the URL:
  • is empty, or longer than 8192 UTF-16 code units (checked before it is parsed),
  • does not target this instance’s redirectUrl (scheme and host compared case-insensitively, the path case-sensitively, ignoring trailing slashes and surrounding whitespace),
  • carries both authMethod and login_type (Portal never sends both), or
  • carries no error parameter and either no token (or an empty or whitespace-only one) or no sign-in marker this SDK recognizes.
That makes it safe to call from a shared deep-link handler alongside your app’s other routes. Otherwise, a redirect that carries ?error=… is .failed(error:), even when it also carries a token or a sign-in marker, and its token is never handed out.
Printing an AuthRedirect — with print, String(describing:), String(reflecting:) or dump — shows <redacted> in place of its token. AuthRedirect.MagicLink.token is a plain String that does not, so hold on to the MagicLink value rather than the bare string, and read token only to pass it to the SDK. The token of an AuthRedirect.OAuth is not public at all: only completeOAuthLogin(_:) reads it.
A magic link signs in whoever opens it, to the account it was sent for. Anyone can get a magic link for their own email address, for example by signing in to your app, and forward it to your user. If your app completed every magic link as soon as it arrived, opening that link would sign your user in to the sender’s account, where they could, for example, fund a wallet the sender controls. Completing a magic link in two steps gives the user a chance to notice a link that isn’t theirs before anything is signed in. It is a safeguard, not a guarantee: it works only if your app shows the email address clearly and the user reads it. An app that still completes magic links in one step skips it entirely. The two steps:
  1. getMagicLinkDetails(_:) reads the email address the link signs in to, without using up the link. It returns a MagicLinkDetails whose email is the full address. Masking it, if you want to, is up to your screen. Printing the value shows <redacted>; read email to display it.
  2. confirmMagicLink(_:) completes the sign-in and returns the same AuthResult as every other sign-in. Call it only after the user confirms, on your app’s own screen, that the email address is theirs.
Portal does not require the lookup before the exchange, and the SDK does not enforce it: the confirmation is your app’s to show. Call getMagicLinkDetails(_:) first in any case — it also reports an expired or already used link before you ask the user anything. Whatever it throws, do not confirm the link: a link whose email the user has not seen must not be exchanged. The SDK provides no UI for this step. MagicLinkConfirmation below holds one confirmation at a time, for SwiftUI or UIKit alike. Create one next to portalAuth and keep it for the life of your app, as completeSignIn(with:) above expects:
Build it with a check your app already has, for example MagicLinkConfirmation(portalAuth: portalAuth, isSignedIn: { PortalHolder.shared.portal != nil }) with PortalHolder from Handle session invalidation. Then show its prompt:
confirm(_:) sets isConfirming before anything awaits, and accepts only the link whose email the prompt showed, so a second tap, or any link delivered while it runs, cannot start another confirmation (to use a different link, the user opens it again afterwards). The prompt stays hidden and the rest of your UI disabled until the exchange ends. Even a second call would not sign the user in twice: the SDK runs confirmations of the same link one at a time and answers a repeat from memory, on the same PortalAuth, while that session is live (see Handle a re-delivered redirect). Every way the flow can end leaves the user somewhere definite: signed in, or at the two-factor prompt, through handle(_:); back at the prompt with a retry message; back on your sign-in screen after Cancel; or reading a notice. If confirming fails for any reason other than PortalAuthError.grantRejected, the pending link is kept and the prompt comes back with a retry message; see Handle a re-delivered redirect for when a retry can succeed.
  • Look a link up once. Each link can only be looked up a few times, and a lookup past that limit throws PortalRequestsError.clientError (a 429). Call getMagicLinkDetails(_:) once per confirmation and keep the email while the user decides, as pending does. A spent or forged link is rejected with .grantRejected before the limit applies.
  • Cancel exchanges nothing. If the user declines, the link is never used and expires on its own, 15 minutes after it is sent.
  • A rejected link is final. .grantRejected from either call means the link has expired, was already used, or is otherwise unusable. Retrying fails the same way, so ask the user to request a new link — unless they already confirmed this link and are signed in, when there is nothing to do.
  • Forget the confirmed link on sign-out. It is only there to route a re-delivered link to confirmMagicLink(_:). Call signedOut().
Other failures, such as the lookup limit, a server error or a dropped connection, are thrown unchanged. Both methods throw PortalAuthError.invalidArgument(name: "token") before sending anything when the token is empty or whitespace-only, and CancellationError when called from a task that is already cancelled. confirmMagicLink(_:) returns .totpRequired when the user has two-factor authentication; see Handle two-factor authentication.

Complete a Google or Apple sign-in

completeOAuthLogin(_:) exchanges the grant of a loginWithGoogle() / loginWithApple() redirect and returns an AuthResult. Pass it the .oauth value parseRedirect(_:) returned:
The grant is exchanged only with the code verifier of the sign-in this device started, so your app does not check which redirects it started: a Google or Apple grant someone else obtained, opened through your redirect URL by a web page, a message or another app, signs nobody in. See Google and Apple sign-ins are bound to the device for the two errors such a redirect throws. An app that uses only signInWith* can ignore every .oauth redirect the OS delivers. The sign-in stays in progress when its exchange fails on a dropped connection or an HTTP error, so the same redirect can be passed in again within the 15 minutes (Portal refuses it if the first attempt spent the grant). The same applies when the Keychain can’t be read: completeOAuthLogin(_:) throws PortalAuthError.sessionStorageFailure without sending anything. signInWithGoogle() and signInWithApple() complete their own callback the same way, and accept only a result for the provider their sheet was opened for: any other callback, a result for the other provider or a magic link, throws PortalAuthSignInError.callbackIncomplete without being exchanged. A grant Portal refuses — already used, expired, issued for another environment, or from a sign-in other than the one in progress on this device — throws PortalRequestsError.unauthorized from completeOAuthLogin(_:) and signInWith*, not PortalAuthError.grantRejected. A Google or Apple sign-in must finish at the provider within 10 minutes and be exchanged within 15 minutes of starting; see Grants are single use.

Handle a re-delivered redirect

iOS can deliver the same redirect twice. parseRedirect(_:) uses up nothing, and getMagicLinkDetails(_:) does not use up the link, though each call counts toward its few lookups. confirmMagicLink(_:), completeOAuthLogin(_:) and signInWith*, which completes through the same path, remember the last grant they exchanged and the AuthResult it produced while your app keeps running. While a PortalAuth remembers a grant it exchanged successfully, it does not send that grant to Portal again:
  • Concurrent calls with the same grant run one at a time. Once the first has succeeded, the others return its result without a request; if it failed, the next one sends its own request (see the retries below).
  • A call after a successful one with the same grant returns the remembered result — the same PortalSession instance — without a request, as long as that session is live.
That memory is deliberately narrow:
  • It holds one grant: the most recent sign-in this PortalAuth instance exchanged. A newer sign-in replaces it, and another instance has its own.
  • It is keyed by the kind of sign-in and the grant, so a magic link is only ever answered by a magic-link completion, and a Google or Apple grant only by a Google or Apple one.
  • It lives in memory, in this process. After the app is terminated, restoreSession() is how a completed sign-in comes back, so restore the session on launch before you route redirects.
A magic link needs one thing from your app. getMagicLinkDetails(_:) always asks Portal and never answers from that memory, so it rejects a link that has already been confirmed with .grantRejected. The SDK cannot tell that case apart from the token alone, so your app remembers which link the user confirmed and sends it straight to confirmMagicLink(_:), as MagicLinkConfirmation does with confirmedLink. Like the SDK’s memory, your app’s lasts only while it runs: after a relaunch, a .grantRejected for a link that arrives while the user is signed in is nothing to do. The replay stops once the remembered session has ended. After portal.clearSession(), or a 401 that Portal received with that session, a repeat call throws without a request: confirmMagicLink(_:) throws PortalAuthError.grantRejected and completeOAuthLogin(_:) throws PortalRequestsError.unauthorized. This needs the Portal to hold that very session: one built from restoreSession() holds a separate copy, which is why signing out also calls clearPersistedSession() (see End the session). clearPersistedSession() forgets the grant altogether. After it, a repeat confirmMagicLink(_:) is sent to Portal, which rejects the spent link with .grantRejected, and a repeat completeOAuthLogin(_:) throws PortalAuthError.oauthFlowNotStarted without a request, because the sign-in it completed is no longer in progress (or PortalRequestsError.unauthorized, from Portal, if a newer sign-in is in progress). Either way you never get a session for a user who is signed out. A failed exchange is not remembered, so calling again with the same grant sends it again; after a dropped connection or an HTTP error, a Google or Apple sign-in stays in progress for that retry. That succeeds only if the failed attempt never reached Portal, because Portal uses up a grant as soon as it receives it; otherwise the retry throws (.grantRejected for a magic link, PortalRequestsError.unauthorized for Google or Apple) and the user starts a new sign-in. The exception is a Keychain write failure, PortalAuthError.sessionStorageFailure, after a successful exchange: that result is remembered, and calling again with the same grant on the same PortalAuth finishes the write without sending the grant. Cancellation stops an exchange only before it starts: a call made from a task that is already cancelled throws CancellationError and sends nothing. Once a call has started, the exchange runs to completion even if its task is cancelled meanwhile — Portal uses up the grant before it answers — and the result is still returned and remembered. A clearPersistedSession() called while a magic link or a two-factor code is being completed waits for it, then deletes the session it persisted and forgets it; the completion still returns that session to its caller, and it keeps working in memory. A Google or Apple completion running on the same PortalAuth is cancelled instead: completeOAuthLogin(_:) or signInWith* throws PortalAuthError.oauthFlowNotStarted rather than return a session the clear is about to delete. One running on another instance completes, and its session survives until the next clear. The clear cannot close a signInWith* sheet that is still open, so close that first, as End the session shows. If your app signed out while a completion ran, discard the result instead of adopting it, as MagicLinkConfirmation, completeOAuth(_:) and signIn(with:from:) do with a sign-out counter captured before the await. On success the session is persisted before it is returned, so a Keychain write failure fails the sign-in with PortalAuthError.sessionStorageFailure rather than handing you a session that will not survive a restart.
Because a redirect can be replayed, anything you do with the result has to be safe to run twice. onSignedIn(_:) above may be called again for the same session, so make it idempotent — adopt the session and move on if you already hold it, rather than re-running one-time setup or pushing a second screen.
Complete each redirect on exactly one PortalAuth instance: two instances built with the same redirectUrl would each try to exchange it, and the second one fails.

Migrate from handleRedirect

handleRedirect(_:) is deprecated in PortalSwift 8.2.0 and will be removed in the next major version. It still works: it reads the URL with parseRedirect(_:) and completes it in one step. For a Google or Apple redirect that is exactly what completeOAuthLogin(_:) does, device binding included: a redirect with no sign-in in progress on this device throws PortalAuthError.oauthFlowNotStarted from either. For a magic link, though, it signs the user in at once, without the confirmation step, so the user gets no chance to notice a link that isn’t theirs. It shares the remembered result with confirmMagicLink(_:) and completeOAuthLogin(_:), but keeps its own errors: a magic link Portal refuses still throws PortalRequestsError.unauthorized rather than PortalAuthError.grantRejected, and a redirect that carries ?error=… throws PortalAuthError.authenticationFailed(error:). For a Google or Apple redirect it throws what completeOAuthLogin(_:) throws. Each time it is given a magic link it logs a deprecation warning at the .warn level. The log level is shared, starts at .none, is reset to .none by every Portal you construct, and can only be raised with portal.setLogLevel(_:) after that (see Configure log level). A redirect is usually completed before any Portal exists, so rely on Xcode’s deprecation warning at the call site. As of 8.2.0, handleRedirect(_:) also returns nil, as parseRedirect(_:) does, for a URL that carries both authMethod and login_type (which it used to exchange as a magic link) and for a token that is only whitespace. Portal never sends either.

Handle two-factor authentication

If your environment requires a second factor, a completed sign-in returns .totpRequired(TotpRequiredResult) instead of a session. Nothing is persisted yet. totpLink is an otpauth:// URI on a user’s first sign-in, when they still have to enroll an authenticator app, and nil once they are enrolled. Unlike the other Portal SDKs, the iOS SDK renders the enrollment QR code for you:
On success, verifyTotp(_:userJwt:) returns the same AuthenticatedResult the non-TOTP path produces, so session is the PortalSession you carry on with — hand it to the same place you would hand a session from confirmMagicLink(_:) or completeOAuthLogin(_:):
verifyTotp(_:userJwt:) posts the code exactly as given, so check that it is six digits before you submit it. The userJwt expires ten minutes after the sign-in reached this step; if it expires, or the app is terminated first, the user starts the sign-in again. Once the code is accepted, completing the same grant again on the same PortalAuth returns the session rather than sending the user back to the prompt, while the app keeps running and that session is live.
A rejected code, an expired userJwt, and one that has already been used all surface as PortalRequestsError.unauthorized, so the SDK cannot tell you which happened. Prompt for the next code from the authenticator app; if that keeps failing, start a new sign-in. There is no way to refresh a userJwt.
totpLink and totpSecret carry the user’s TOTP secret. Never log, persist, or send them to analytics. If you offer a “Copy key” button, write to the pasteboard with UIPasteboard.general.setItems(_:options:), using .localOnly: true and a short .expirationDate, so the secret stays off Universal Clipboard and does not linger.
A userJwt the SDK cannot read throws PortalAuthError.invalidUserJwt(detail:) before the network call, so a malformed JWT never costs the user a live code. For what the second factor is and how to reset an enrollment, see Two-factor authentication.

Initialize Portal from the session

Pass the session as credentials. Everything else about Portal is unchanged, including how you register backup methods.
portal.credentials is the credential the instance authenticates with — the PortalSession here, or a StaticCredentials wrapping the key for a Portal built from a Client API Key. Read the current token with try portal.credentials.getToken(). session.endUserId is never secret, so it is the identifier to log and to key your own per-user state on. onSignedIn(_:) in the examples above is where you do this, for example with PortalHolder.adopt(_:) from Handle session invalidation, which builds the Portal and subscribes to invalidation in one step.
portal.apiKey is an empty string on a session-backed instance and is deprecated. Do not read it or forward it anywhere: it carries no credential. Use portal.credentials instead.
The session token is attached only to RPC URLs that are Portal’s own: portalhq.io or portalhq.dev and their subdomains over HTTPS, or a host and port this Portal was configured with (apiHost, mpcHost, enclaveMPCHost). Any other withRpcConfig entry, including your own gateway, is called without it, so an end user’s session token is never handed to a third party. localhost and 127.0.0.1 qualify only when their host and port match the apiHost you configured, so a local Anvil or Hardhat node never receives it.

Create or reuse the wallet

A returning end user keeps the client and wallet they already have, so check the wallet’s lifecycle state before creating anything. Create a wallet only when the environment asks you to, via autoCreateWallet.
A restore on launch and a redirect can arrive at the same time, so run one adoption at a time; otherwise two code paths can both decide the user has no wallet. See Create a wallet for the full wallet lifecycle, and Manage wallet lifecycle states for the helpers used above.

Restore the session on launch

restoreSession() rebuilds the session from the Keychain, without a network call, so a returning user does not sign in again.
nil means “not signed in”, and that includes an entry the SDK can see but cannot parse. No caller action makes that readable, so the SDK clears it and reports nil rather than failing your launch. PortalAuthError.sessionStorageFailure is reserved for the Keychain failing this time, which may pass on the next attempt.
A restored session is a credential worth trying, not proof that it is still valid. Validity is only discovered on the first authenticated call, which invalidates the credential on a 401.

End the session

There are three ways a session ends, and they are not interchangeable.
Call both on sign-out, each in its own do, so a failure in one does not skip the other. clearSession() ends the credential your Portal holds, but it does not reach what PortalAuth keeps: its memory of the last grant it exchanged, a session from an accepted two-factor code still waiting to be written, a session a sign-in stored after your Portal was built, or a Google or Apple sign-in in progress. That memory can hold a different PortalSession object — from an earlier redirect in this process, when your Portal was built from restoreSession() — and a redirect delivered again would replay it. Before anything awaits, the sample closes an open sign-in sheet and forgets your app’s own sign-in state: the magic link the user confirmed, and the Portal. clearPersistedSession() cancels a Google or Apple sign-in in progress, so a browser redirect or a sheet callback that arrives afterwards is refused, but it cannot close a sheet that is still open. It waits for a magic link or a two-factor code that is already being completed, then deletes what it stored. That completion still returns its session to its caller, and that session keeps working in memory, so the sign-out counter makes sure it is discarded rather than adopted. After clearSession() this Portal is spent: every authenticated call fails with PortalCredentialError.sessionInvalidated. Construct a new Portal from the next sign-in rather than reusing it. On a Portal built from a Client API Key the call does nothing — there is no session to end. Both operations throw PortalAuthError.sessionStorageFailure if the delete fails; for clearSession() the in-memory token is dropped either way, and calling it again retries the delete.
clearPersistedSession() is not a sign-out. It stops a future restoreSession() from returning the session, but a Portal already holding the credential keeps signing transactions. To sign a user out, call portal.clearSession().
clearPersistedSession() also cancels the Google or Apple sign-in in progress for this auth environment, and an exchange completeOAuthLogin(_:) or signInWith* is already running on this instance (not one on another instance), which then throws PortalAuthError.oauthFlowNotStarted instead of returning a session. Wait for it to return before starting a new sign-in. Calling it after loginWithGoogle() or loginWithApple() has returned a URL, or while a sign-in sheet is open, abandons that sign-in, so do that only on purpose. A sign-in that has already reached its two-factor step is not cancelled: its grant is already spent, and verifyTotp(_:userJwt:) can still complete it. To abandon it, discard its userJwt.
There is no server-side revoke endpoint, so both operations are local sign-outs. The token itself stays valid until the backend expires it: every authenticated request extends it to 24 hours later, until seven days after it was issued. See API Keys for session lifetimes.
Neither operation deletes the wallet’s signing shares — that is what the separate Keychain namespace buys you. The session lifecycle and the wallet lifecycle are separate: when the user signs in again, they continue with the same wallet, provided that wallet is otherwise still available to them.

Handle session invalidation

When the backend rejects the credential with a 401, the session ended somewhere your app cannot see and the user has to sign in again. Subscribe where the Portal lives, and turn the one-shot callback into state your UI can observe:
When sessionEnded turns true, route to sign-in. The SDK has already invalidated the credential and deleted its stored copy, so do not call portal.clearSession() again; first call SignInSheet.close(), magicLinkConfirmation.signedOut() and PortalHolder.shared.signedOut(), then portalAuth.clearPersistedSession() so the replay memory cannot serve the dead session back. Do this before you show the sign-in screen: the call also cancels a Google or Apple sign-in in progress. The callback fires at most once for a credential, and it is not fired by portal.clearSession() — you already know about a sign-out you asked for. It never fires for a Portal built from a Client API Key, which is custodian-owned and has no session to end; that subscription returns PortalSessionInvalidationHandle.spent. A rejection that happened before you subscribed is not lost. Portal starts an authenticated request as soon as it is constructed, and if that is the request the backend rejects, a listener you add afterwards still runs, once, on the main actor. Do not subscribe again from inside the listener: the instance is spent, and a new subscription would be called as well. cancel() on the returned handle removes the listener, suppresses a delivery that is already queued but has not run, and is safe to call more than once or from inside the listener. The handle is not cancelled when it is deallocated, so keep it if you intend to unsubscribe. What triggers it is a 401 on any request that carried the Portal session token to a Portal-owned host — Portal’s own domains, or a host you configured on Portal or PortalAuth — and an MPC AUTH_FAILED from a wallet or signing operation. What cannot trigger it is a request the SDK never authenticated with the session: a third-party RPC gateway, Google Drive, or a passkey the user failed or cancelled.
Still handle errors from your wallet and signing calls as well as subscribing here. The callback tells you the session ended, not which call failed. The request that saw the 401 fails with its own error, such as PortalRequestsError.unauthorized, and every later call on that Portal throws PortalCredentialError.sessionInvalidated.
As with a sign-out, an invalidated session does not delete the wallet’s signing shares — only the credential is gone. Wallet state cannot be read without a session, so treat it as unknown until the user signs in again rather than as evidence the wallet is missing.

Handle errors

Client Auth surfaces three error types, plus the transport’s own errors. PortalAuthError — a sign-in that could not be completed: grantRejected and oauthFlowNotStarted are new in PortalSwift 8.2.0. PortalAuthError is a public enum, so an exhaustive switch over it, with no default, needs a case for each before it compiles against 8.2.0.
How you recover from sessionStorageFailure depends on where it came from:
  • restoreSession(), clearPersistedSession(), clearSession(): storage failed this time and may work on the next attempt, so retrying is right.
  • loginWith*: the sign-in could not be stored, so none was started. Retrying is right.
  • signInWith*: call it again, which starts a new sign-in. The sign-in could not be stored (none was started), could not be read when the sheet returned (nothing was sent), or the grant was spent and only the session write failed.
  • verifyTotp(_:userJwt:): the code was accepted and only the Keychain write failed. Call verifyTotp again with the same userJwt — the SDK finishes the write and returns the session without another network call.
  • confirmMagicLink(_:): the grant is already spent and only the write failed. Calling it again with the same token, on the same PortalAuth, finishes the write instead of re-sending the grant.
  • completeOAuthLogin(_:): pass the same redirect to the same PortalAuth again. If the Keychain could not be read, nothing was sent yet; if only the session write failed, the grant is already spent and the SDK finishes the write instead of re-sending it.
PortalAuthSignInError — thrown by signInWithGoogle() and signInWithApple() only. Its raw values are the Web SDK’s popup error codes: PortalCredentialError — a credential that could not be turned into a token. Branch on requiresReauthentication, or on reason for the value shared with the other Portal SDKs: Apart from rateLimited and accountAbstractionUnavailable, transport failures are not remapped, with one more exception: a 401 from getMagicLinkDetails(_:) or confirmMagicLink(_:) arrives as PortalAuthError.grantRejected. Every other 401 arrives as PortalRequestsError.unauthorized. From any PortalAuth call it can mean the Auth Environment ID is wrong or authentication is switched off for the environment; beyond that, what it means depends on the call that threw it:
The shared When a sign-in fails table, on iOS:

Keep credentials out of logs

  • Never log the grant token, the raw redirect URL, the userJwt, the totpLink, the session token or the user’s email address — including the email getMagicLinkDetails(_:) returns. Show that one on your confirmation screen and nowhere else. Safe to log: endUserId, clientId, the Auth Environment ID and the auth method.
  • The PortalSession that PortalAuth returns, AuthRedirect, MagicLinkDetails, TotpRequiredResult and PortalCredentialError redact their secrets from String(describing:), String(reflecting:) and dump, so printing a redirect, a magic link’s details, a result or an error does not leak the grant, the email, the session token, the userJwt or the totpLink. Read MagicLinkDetails.email only to display it.
  • The Auth Environment ID identifies an environment; it does not authenticate a caller. Treat it like an OAuth client ID: keep it in configuration, but do not rely on it staying secret.

Next Steps

Now that your user is signed in, create a wallet and send tokens. For every PortalAuth method, see the PortalAuth reference. For the dashboard and provider configuration behind this flow, see Authentication.