PortalSession that it passes straight to
Portal. No login system of your own, and no server-side call to mint a
Client Session Token.
Your app owns three things the SDK deliberately does not: when a sign-in
starts, how the authorize URL is opened, and how the redirect gets back
to you. PortalAuth never opens a browser and never registers a deep-link
handler.
Client Auth requires
@portal-hq/core 5.0.0 or later.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
PortalAuth itself needs no new JavaScript package. It ships in
@portal-hq/core, and the session is stored with react-native-keychain,
which @portal-hq/keychain already requires.
You do need to rebuild your app’s native code. Google and Apple sign-ins use
native code in @portal-hq/core to bind each sign-in to the device. After you
upgrade to 6.0.0 or later, run pod install on iOS and rebuild the
iOS and Android apps. Until you rebuild,
loginWithGoogle() and loginWithApple() throw an error asking you to rebuild
the app, and no sign-in starts.
To give a reinstalled iOS app a clean slate (see
Start a fresh iOS install from a clean slate),
you also need storage that is deleted with the app. This guide uses
@react-native-async-storage/async-storage;
any equivalent works. The examples in this guide include that check; if you
leave it out, drop the clearSessionLeftByPreviousInstall() and
markInstallSignedIn() calls from them.
Exclude the keychain from backups (Android)
On Android,react-native-keychain stores the session, and your wallet’s key
shares, in one file, encrypted with a key held in the Android Keystore. Android
Auto Backup and device-to-device transfer copy that file but not Keystore
keys, so a restored device holds entries it can no longer decrypt.
restoreSession() then rejects with PortalKeychainReadError instead of
resolving null (see Restore the session on launch),
and reading the wallet’s shares fails the same way.
Exclude the file, so that a restored device starts like a fresh install: no
session and no wallet on the device. The user signs in again and recovers the
wallet from its backup, as on any new device. Newer versions of
react-native-keychain keep the file in datastore/, and older ones in
SharedPreferences, so exclude both.
The rules only apply to backups taken after your app ships them. A device
restored from an earlier backup still gets the file, and restoreSession()
rejects with PortalKeychainReadError there.
<application> tag in android/app/src/main/AndroidManifest.xml at
both. Which one applies depends on the device’s OS version and on your app’s
targetSdk: on Android 12 and later, an app that targets 31 or higher uses
dataExtractionRules, and an app that targets less still uses
fullBackupContent. If your app already has backup rules, add the <exclude>
lines to them instead.
android:fullBackupContent or
android:dataExtractionRules, the manifest merge fails. Add
tools:replace="android:fullBackupContent,android:dataExtractionRules" to the
<application> tag (with xmlns:tools="http://schemas.android.com/tools" on
<manifest>), and copy that library’s rules into your files.
Keep the rules even with android:allowBackup="false". For an app that targets
Android 12 or later, that turns off cloud backup but not device-to-device
transfer, which only the <device-transfer> exclusions cover.
Register your redirect
The OS only delivers a redirect to your app if you register its scheme natively. For a redirect URL ofmyapp://auth/callback, register the scheme and
make sure a returning redirect reaches the running app.
- iOS
- Android
Register the scheme in Registering the scheme is not enough on its own. A cold start arrives through
Without this,
Info.plist:launchOptions, which Linking.getInitialURL() reads, but the usual Client
Auth path — the browser returning to an app that is still running in the
background — needs your AppDelegate to forward the URL:Linking.addEventListener('url', …) never fires for a warm or
backgrounded app and the sign-in appears to hang.The notification is posted directly because React-RCTLinking ships only its
.m/.mm sources, so RCTLinkingManager.h is not a public header and the
class is not visible from Swift. In an Objective-C AppDelegate you can call
[RCTLinkingManager application:app openURL:url options:options] instead — it
posts the same notification.Create a PortalAuth
Create one long-livedPortalAuth and reuse it. A Google or Apple sign-in in
progress is kept in the device keychain, so it survives your app being
backgrounded, or killed while the browser is open. Instances created with the
same authEnvironmentId share the stored session and the sign-in in progress.
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.
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 your redirect handler must always be ready for it.
Start a sign-in
Google or Apple
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.
Linking.openURL hands off to the system browser, which is what the Portal
example app does and what Google’s OAuth policy requires. You can instead use a
native auth-session API such as ASWebAuthenticationSession or Android Custom
Tabs, but be careful: on Android the Custom Tab redirect also fires your
intent filter, so the session’s own result and your deep-link listener will both
deliver the same redirect. Complete it from one path only — see
Redelivered redirects.Google and Apple sign-ins are bound to the device
EveryloginWithGoogle() and loginWithApple() call binds the new sign-in to
this device with PKCE. The SDK
creates a one-time secret and stores it in the device keychain. It sends Portal
only a hash of the secret when the sign-in starts, and the secret itself only
when it 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 a sign-in that can’t be bound
fails before any authorize URL is returned.
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 can’t complete.
- One sign-in at a time. On a device, each auth environment has one Google or Apple sign-in in progress. Starting a new one replaces it, and a redirect from the earlier attempt can no longer complete. 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 also gives the user 10
minutes to finish at Google or Apple. After that, the redirect comes back with
an error and fails with
ProviderRejected(see Grants are single use). - Clearing the stored session cancels it.
clearPersistedSession()also cancels a sign-in in progress;portal.clearSession()does not. See End the session.
OAuthFlowNotStarted when the device
has no Google or Apple sign-in in progress, before anything is sent to Portal,
or with GrantRejected when Portal refuses it, as it does for a sign-in that
was replaced. In either case, start a new sign-in.
Email magic link
sendMagicLink() resolves 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 completes it only after the user confirms the
email address the link signs in to (see
Confirm a magic link).
Every call sends a real email, and sends are rate limited to 10 per address per
minute. Never retry automatically; make a resend an explicit user action.
Complete the sign-in
parseRedirect(), completeOAuthLogin(), getMagicLinkDetails() and
confirmMagicLink() require @portal-hq/core 6.0.0 or later. Earlier versions
complete every sign-in through handleRedirect(), which is now deprecated (see
Migrate from handleRedirect()).redirectUrl.
Completing it takes two steps:
- Read the redirect with
parseRedirect(). It runs locally and synchronously, sends nothing to Portal, and tells you which kind of sign-in the URL completes. - Complete it with the method for that kind:
- Google or Apple (
AuthMethod.Google,AuthMethod.Apple): callcompleteOAuthLogin(redirect.token). - Magic link (
AuthMethod.EmailMagicLink): callgetMagicLinkDetails(redirect.token), show the user the email, and callconfirmMagicLink(redirect.token)only once they confirm it. See Confirm a magic link.
- Google or Apple (
completeOAuthLogin() and confirmMagicLink() resolve with the same result:
a session, or a two-factor challenge (see
Handle two-factor authentication). On
success the session is persisted before it is returned.
parseRedirect() returns a ParsedRedirect, with loginType and token, or
null when the URL isn’t a Client Auth result for this instance:
- it doesn’t target your
redirectUrl, or carries notoken, - it carries an unknown sign-in marker, or both
login_typeandauthMethod, or - it is longer than 8192 characters.
null lets the rest of your router handle the URL. parseRedirect() throws
PortalAuthError with ProviderRejected only when a URL to your redirectUrl
carries ?error=…: the provider sent the user back without completing the
sign-in.
Register the listener before you open any browser, and read getInitialURL()
once per process in case the redirect is what launched your app. Keep that
latch at module scope rather than in component state: getInitialURL() keeps
returning the launch URL for the lifetime of the process, so a per-component
guard lets a remount handle a grant that has already been used.
ParsedRedirect keeps the token out of JSON.stringify, string conversion and
object spreads, so logging a ParsedRedirect doesn’t leak the grant. Read
redirect.token only to pass it to the SDK. A debugger, or any code that reads
token, still sees it.Redelivered redirects
Operating systems do re-deliver deep links, so the same redirect can reach your handler twice.parseRedirect() and getMagicLinkDetails() don’t use up a
grant, so calling them again sends nothing that changes the sign-in.
Route every redirect through exactly one handler in your app. The behavior
below is a safety net, not something to rely on: once the app restarts or the
session ends, handling the same redirect again fails because its grant has
already been spent. On launch, restore the stored session instead of handling
the redirect again.
On one PortalAuth, completeOAuthLogin(), confirmMagicLink() and the
deprecated handleRedirect() send a grant to Portal at most once, for both
kinds:
- Concurrent calls with the same token share one request and resolve to the same result, or reject with the same error.
- A call after a successful one with the same token resolves to the same result without another request, as long as that session is still live.
- the session has ended, through
portal.clearSession(),clearPersistedSession()or the backend invalidating it, - another sign-in has completed on the same
PortalAuth, or - the app has restarted, or you use a different
PortalAuthinstance.
GrantRejected, and a Google or Apple
redirect fails with OAuthFlowNotStarted, or with GrantRejected if another
Google or Apple sign-in has started since.
A magic link redelivered after it was confirmed is already used, so
getMagicLinkDetails() rejects it with GrantRejected: it always asks Portal.
When the user is already signed in, that is expected rather than a failure. The
hook above ignores it in that case.
A failed completion is never remembered: the error is rethrown unchanged, and
calling the same method again with the same token sends a new request. For
Google or Apple, the sign-in in progress is kept, including when the keychain
can’t be read, for example before the device’s first unlock after a restart.
Portal uses up a grant as soon as it receives it, before it creates the
session, so a retry succeeds only when the failed attempt never got that far,
typically because the request never reached Portal. After a server error, or a
connection that dropped once Portal had the request, the grant is used and the
retry rejects with GrantRejected: start a new sign-in.
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 through the deprecatedhandleRedirect() skips it entirely.
The two steps:
getMagicLinkDetails(token)reads the email address the link signs in to, without using up the link. It resolves with{ email }, the full address. Masking it, if you want to, is up to your app.confirmMagicLink(token)completes the sign-in. Call it only after the user confirms, on your app’s own screen, that the email address is theirs.
pendingMagicLink, isConfirming, confirmMagicLink and
cancelMagicLink from the hook in Complete the sign-in.
A second tap can’t use up the link twice: the SDK shares one request between
concurrent confirmations of the same link and replays a successful one (see
Redelivered redirects). The hook’s guard and the
disabled buttons keep your screen from running two confirmations at once.
Cancelling uses up nothing, so the link stays valid until it expires.
If confirming fails for any reason other than GrantRejected, the hook keeps
the pending link so the user can try again. Don’t promise that the retry will
work: it succeeds only if the failed attempt never reached Portal, and
otherwise rejects with GrantRejected.
Other failures, such as a rate limit, a server error or a dropped connection,
are rethrown unchanged. An error response from Portal is an
HttpError
(exported from @portal-hq/core) with its HTTP status. getMagicLinkDetails()
is rate limited for each link: a link looked up too many times rejects with an
HttpError whose status is 429. Don’t poll it: call it once per redirect,
keep the result while the user decides, and call it again only when the user
asks.
Both methods throw before sending anything when the token is empty.
Migrate from handleRedirect()
handleRedirect() is deprecated and will be removed in the next major version.
It still works, and completes an OAuth redirect exactly as
completeOAuthLogin() does. 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 logs a deprecation warning each time it does, when your
logLevel shows warnings. It shares in-flight requests and the
remembered result with completeOAuthLogin() and confirmMagicLink(), so a
redirect completed through either path resolves the same way through the other.
Send every redirect that
parseRedirect() reads as a magic link to the
confirmation step, never to handleRedirect().
Handle two-factor authentication
If your environment requires a second factor, a completed sign-in resolves withstatus: 'totpRequired' instead of a session. Nothing is persisted yet.
totpLink is an otpauth:// URI on a user’s first sign-in — render it as a QR
code for their authenticator app — and null once they are enrolled.
On success, verifyTotp() resolves the same shape the non-TOTP path produces,
so result.session is the PortalSession you carry on with — hand it to the
same place you would hand a session from completeOAuthLogin() or
confirmMagicLink():
createPortal from
Initialize Portal from the session:
Rendering the QR code is your app’s job; Portal does not ship a QR component.
Any React Native QR library works — pass
challenge.totpLink to it verbatim.Initialize Portal from the session
Pass the session ascredentials. Everything else about Portal is unchanged —
including backup, which is still required.
credentials and apiKey are mutually exclusive — passing both throws.
Create or reuse the wallet
A returning end user keeps the client and wallet they already have, so check for addresses before creating anything. Create a wallet only when the environment asks you to, viaautoCreateWallet.
Restore the session on launch
restoreSession() rebuilds the session from secure storage so a returning user
does not sign in again.
restoreSession() resolves null only when nothing is stored. It rejects in
two cases:
- The keychain could not be read. It rejects with
PortalKeychainReadError(from@portal-hq/keychain,code: 'KEYCHAIN_READ_FAILED') after retrying the read once, and leaves the stored session in place, because the failure may be temporary.nativeCodeholds thereact-native-keychainerror code, such asE_CRYPTO_FAILED. Signing in again replaces the unreadable session; if you want it gone before that, callclearPersistedSession(). On Android, a session restored from a device backup always fails this way (see Exclude the keychain from backups). - The stored session is corrupt. It rejects with an error asking you to
call
clearPersistedSession()and sign in again.
PortalKeychainReadError from restoreSession() requires @portal-hq/core and
@portal-hq/keychain 6.1.0 or later. Earlier versions reject with the raw
react-native-keychain error, so the example above treats a keychain read
failure as a corrupt session and clears it.Start a fresh iOS install from a clean slate
Keychain items survive app deletion, so on iOS a reinstalled app can find the previous install’s session and sign that user, possibly a previous owner of the device, straight back in. AsyncStorage is deleted with the app, which makes it a per-install marker: clear the persisted session the first time an install launches.clearSessionLeftByPreviousInstall() at launch, and wait for it before
you handle the launch URL or any redirect, call restoreSession(), or start a
sign-in. A first launch can be opened by a redirect, and
clearPersistedSession() cancels a sign-in in progress; a clear still running
when a sign-in persists its session would also delete it. The check runs once
per launch, so you can await it from each of those places, and a failed check
isn’t retried until the next launch. When it resolves false, skip
restoreSession() and show the sign-in screen.
Call markInstallSignedIn() wherever your app receives the signed-in session,
and wait for it. Otherwise, after a failed clear, the next launch’s retry
deletes the session the user just signed in with. A failed marker write only
signs the user out on the next launch, so log it rather than failing the
sign-in.
The examples in this guide already do both:
signInWithProvider()in Google or Apple andrestore()in Restore the session on launch wait for the check.- The
useClientAuthhook in Complete the sign-in waits for it at the start ofhandleUrl, which covers the launch URL and later redirects, andapplyResult()callsmarkInstallSignedIn(). verifyTotp()in Handle two-factor authentication callsmarkInstallSignedIn(), since it stores a session without going throughapplyResult().
End the session
There are three ways a session ends, and they are not interchangeable.Call
clearPersistedSession() before loginWithGoogle() or
loginWithApple(), never after one has returned its URL. It cancels the
sign-in in progress, so that sign-in’s redirect fails with
OAuthFlowNotStarted.If
clearPersistedSession() runs while completeOAuthLogin(),
confirmMagicLink() or handleRedirect() is waiting for Portal, that
completion stores nothing: it rejects with OAuthFlowNotStarted for Google or
Apple, and with GrantRejected for a magic link. Portal may already have used
the grant, so start a new sign-in rather than retrying it.There is no server-side revoke endpoint, so both operations are local
sign-outs. The token itself stays valid until the backend expires it. See
API Keys
for session lifetimes.
Neither operation deletes the wallet’s signing shares. 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.
portal.clearSession() — you already know
about a sign-out you asked for.
Subscribe from something that lives as long as the Portal it belongs to. The
callback is not replayed, so if the only subscriber is inside a screen that has
been unmounted by the time the session ends, the event is missed and your app
carries on looking signed in.
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 two error types, branched on theirreason, and
restoreSession() can also reject with a storage error,
PortalKeychainReadError (see below).
PortalAuthError — a sign-in that could not be completed:
PortalCredentialError — a credential that could not be turned into a token:
restoreSession() can also reject with PortalKeychainReadError when the
keychain can’t be read. Branch on its code, 'KEYCHAIN_READ_FAILED' (see
Restore the session on launch).
Other failures are rethrown unchanged. For example, a magic link whose details
are looked up too many times rejects with an HttpError whose status is
429 (see Confirm a magic link). A user declining the
magic link confirmation is not an error: nothing is exchanged and the link
expires on its own. For the failure cases every SDK shares, see
When a sign-in fails.