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 anASWebAuthenticationSessionsheet 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 withparseRedirect(_:)and complete withcompleteOAuthLogin(_:).
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
- Authentication enabled for your environment, with at least one sign-in method and your Auth Environment ID to hand (see Enable authentication)
- The sign-in methods you want configured — Email magic links, Google OAuth, or Apple OAuth
- A redirect URL on your environment’s allow list (see Redirect URLs)
- A working Portal integration (see Getting Started)
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 ofmyapp://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.
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.
Create a PortalAuth
Create one long-livedPortalAuth and reuse it.
A blank
authEnvironmentId or redirectUrl throws
PortalAuthError.invalidArgument(name:). The initializer makes no network or
Keychain call.
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.
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.
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.
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.
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.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
PortalAuthinstance 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 onePortalAuthinstance, that is the one started last; across instances, it is whichever stored its verifier last. (A secondsignInWith*call on the same instance while a sheet is open throwssignInInProgressinstead.) 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()orloginWithApple()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 exchangecompleteOAuthLogin(_:)orsignInWith*is already running on that same instance.portal.clearSession()does not. See End the session.
- 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
PortalAuthinstance, or afterclearPersistedSession()), it is more than 15 minutes old, or it was cancelled —completeOAuthLogin(_:)throwsPortalAuthError.oauthFlowNotStarted. Nothing is sent to Portal, unlessclearPersistedSession()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(_:)throwsPortalRequestsError.unauthorized.
error instead
of a grant is .failed(error:) from parseRedirect(_:); see
Read the redirect.
Email magic link
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.
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.PortalAuthError.grantRejected from getMagicLinkDetails(_:), which is your
cue to offer a new link.
Complete the sign-in
parseRedirect(_:), getMagicLinkDetails(_:), confirmMagicLink(_:) and
completeOAuthLogin(_:) require PortalSwift 8.2.0 or later.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:- SwiftUI
- UIKit (scene delegate)
- UIKit (app delegate)
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
authMethodandlogin_type(Portal never sends both), or - carries no
errorparameter and either notoken(or an empty or whitespace-only one) or no sign-in marker this SDK recognizes.
?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.Confirm a magic link
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:getMagicLinkDetails(_:)reads the email address the link signs in to, without using up the link. It returns aMagicLinkDetailswhoseemailis the full address. Masking it, if you want to, is up to your screen. Printing the value shows<redacted>; reademailto display it.confirmMagicLink(_:)completes the sign-in and returns the sameAuthResultas every other sign-in. Call it only after the user confirms, on your app’s own screen, that the email address is theirs.
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:
MagicLinkConfirmation(portalAuth: portalAuth, isSignedIn: { PortalHolder.shared.portal != nil })
with PortalHolder from Handle session invalidation.
Then show its prompt:
- SwiftUI
- UIKit
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(a429). CallgetMagicLinkDetails(_:)once per confirmation and keep the email while the user decides, aspendingdoes. A spent or forged link is rejected with.grantRejectedbefore 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.
.grantRejectedfrom 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(_:). CallsignedOut().
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:
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
PortalSessioninstance — without a request, as long as that session is live.
- It holds one grant: the most recent sign-in this
PortalAuthinstance 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.
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.
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:
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 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 ascredentials. 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.
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, viaautoCreateWallet.
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.
End the session
There are three ways a session ends, and they are not interchangeable.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() 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 a401, 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:
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.
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.
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:
Keep credentials out of logs
- Never log the grant token, the raw redirect URL, the
userJwt, thetotpLink, the session token or the user’s email address — including the emailgetMagicLinkDetails(_:)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
PortalSessionthatPortalAuthreturns,AuthRedirect,MagicLinkDetails,TotpRequiredResultandPortalCredentialErrorredact their secrets fromString(describing:),String(reflecting:)anddump, so printing a redirect, a magic link’s details, a result or an error does not leak the grant, the email, the session token, theuserJwtor thetotpLink. ReadMagicLinkDetails.emailonly 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 everyPortalAuth method, see the PortalAuth reference.
For the dashboard and provider configuration behind this flow, see
Authentication.