- The Client Session Token never reaches your page. The SDK runs in a hidden
iframe on the Portal origin, and the token stays there.
portal.apiKeystaysundefined. portal.authis the host-facing API. Every method exceptparseRedirect(), which reads a URL locally, proxies into the iframe, because/api/v3/auth/*is not reachable cross-origin from your page.restoreSession()returns identity, not a credential — anendUserIdand nothing more.
Portal constructor after signing in: the same
instance you configured is the one that becomes authenticated.
Client Auth requires
@portal-hq/web 4.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, pointing at a callback route in your app (see Redirect URLs)
- A working Portal integration (see Getting Started)
Choose an authentication mode
The Web SDK accepts four credential modes. Configure exactly one — the SDK does not reject more than one, and resolves them in a fixed order:clientAuth,
then apiKey, then authToken, then authUrl.
The first three assume you already have a client and are authenticating it; see
Web authentication methods. Use
clientAuth
when you want Portal to identify the user and create the client as part of the
sign-in.
Configure Portal for Client Auth
PassclientAuth instead of a credential. The iframe boots unauthenticated and
waits for a sign-in.
isAccountAbstracted only takes effect on a user’s first sign-in. A returning
user keeps the client they already have.Handle the unauthenticated first state
Read this before writing any sign-in code. APortal configured for Client Auth posts authenticationRequired during
configuration and stops there — it does not become ready until a session is
adopted. onAuthenticationRequired is replayed to late subscribers, so you
cannot miss it by subscribing a moment too late.
Three signals are available, and each answers a different question:
onReady answers a question about the SDK, not about your user. Do not treat it
as proof that someone is signed in — see the warning below.
What a session begins is the result of completing a sign-in —
completeOAuthLogin(), confirmMagicLink() or verifyTotp() — or of
restoreSession(). Those return values are the authoritative signal that
someone is now signed in, so keep the answer in one place your app owns:
Until a session is adopted the iframe never reaches
ready, so a loading state
that waits only for onReady never resolves. Gate wallet and API calls on
onReady; gate your sign-in UI on onAuthenticationRequired.Check which methods are enabled
autoCreateWallet is a signal for your app — nothing in the SDK or the API acts
on it. Check for an existing wallet before creating one; a returning end user
keeps the wallet they already have. See Create a wallet.
A two-factor requirement is not visible here. It only appears when a
sign-in is completed, so your callback route must always be ready for it.
Start a sign-in
Google or Apple
getAuthorizeUrl() returns a provider URL for your app to navigate to. The
sign-in completes later, on your callback route.
Offer these controls only while nobody is signed in — see
Handle the unauthenticated first state.
Google and Apple sign-ins are bound to this tab
This binding requires
@portal-hq/web 5.0.0 or later. Earlier versions don’t
bind a sign-in to the tab that started it. If you serve or proxy the Portal
iframe yourself, serve the 5.0.0 iframe.getAuthorizeUrl() call binds the new sign-in to the current browser tab
with PKCE. The Portal iframe creates a
one-time secret and keeps it in its own storage for this tab, where your page
can’t read it. 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, so a callback
can’t complete a sign-in that another browser started. You don’t pass or store
anything yourself, and getAuthorizeUrl() returns a URL only once the secret
is stored.
This changes how sign-ins behave:
- Finish in the tab that started it. The provider must return the user to your callback route in the same tab. Keep that route on the same site as the page that starts the sign-in, because browsers can keep the Portal iframe’s storage separately for each site. A callback that opens in another browser can’t complete, and one that opens in another tab generally can’t either.
- One sign-in at a time. Each auth environment has one Google or Apple sign-in in progress per tab. Starting a new one replaces it, and a callback from the earlier attempt can no longer complete. A magic link is unaffected.
- Finish within 15 minutes. The tab keeps a sign-in for 15 minutes after
getAuthorizeUrl()returns, and a callback handled later can’t complete. Portal also gives the user 10 minutes to finish at Google or Apple. After that, the callback comes back with an error andparseRedirect()throws aProviderRejectedError(see Grants are single use). - Signing out cancels it.
clearSession()also cancels a sign-in in progress. See Sign out.
- If this tab has no Google or Apple sign-in in progress,
completeOAuthLogin(), like the deprecatedhandleRedirect(), rejects with an error whoseidisAuthErrorId.OAuthFlowNotStarted, and nothing is sent to Portal. - If this tab has a different sign-in in progress, for example because a new
one replaced it, Portal refuses the callback’s grant. That error carries no
id.
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 at your callback
route when the user opens the link. Your callback 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.
Build the callback route
parseRedirect(), completeOAuthLogin(), getMagicLinkDetails(),
confirmMagicLink(), AuthErrorId and TotpErrorId require @portal-hq/web
5.0.0 or later. Earlier versions complete every sign-in through
handleRedirect(), which is now deprecated (see
Migrate from handleRedirect()).- Read the callback URL with
parseRedirect(). It runs locally and synchronously, sends nothing to the Portal iframe or 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:
the signed-in identity, or a two-factor challenge (see
Handle two-factor authentication). On
success the iframe stores the session and adopts it before the result reaches
your page.
parseRedirect() returns a ParsedRedirect, with loginType and token, or
null when the URL isn’t a Client Auth result for this page:
- it doesn’t target
clientAuth.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 a
ProviderRejectedError, whose id is AuthErrorId.ProviderRejected, only
when a URL to your redirectUrl carries ?error=…: the provider sent the user
back without completing the sign-in. It also throws when
clientAuth.redirectUrl isn’t configured, since no URL can be matched.
Because the page loads fresh, wait for the SDK before completing the sign-in —
and subscribe to both onReady and onAuthenticationRequired. A Client
Auth Portal does not become ready until a session is adopted, so on the usual
fresh callback load only onAuthenticationRequired fires. If the route is
instead reached with a session already live — client-side navigation, or a
restoreSession() that resolved during startup — portal.ready is already
true and onReady invokes your callback synchronously. Either can be the one
that runs, so guard the work to a single run.
ParsedRedirect keeps the token out of JSON.stringify and string conversion,
so logging a ParsedRedirect doesn’t leak the grant. Read redirect.token only
to pass it to the SDK.forgetCallbackUrl() changes the address bar with history.replaceState(). If
your app uses a client-side router, put the redirect URL back through that
router’s own replace navigation instead, such as router.replace(), so the
router’s record of the current URL stays in step with the address bar.Reloaded callbacks
A browser doesn’t deliver a callback twice to the page that handled it, but the user can reload the page or open the same link again.parseRedirect() and
getMagicLinkDetails() don’t use up a grant, so calling them again sends
nothing that changes the sign-in.
Route every callback through exactly one handler in your app. The behavior
below is a safety net, not something to rely on: once the page reloads or the
session ends, handling the same callback again fails because its grant has
already been spent. On load, restore the stored session instead of handling the
callback again.
Within one page load, completing the same sign-in twice doesn’t sign the user
in twice. The Portal iframe handles completeOAuthLogin(),
confirmMagicLink() and the deprecated handleRedirect() one call at a time,
so a second call with the same token waits for the first:
- If the first call succeeded, the second resolves to the same result without contacting Portal, as long as the session it created is still the current one and hasn’t ended. For a two-factor challenge, it gets the same challenge back while that step is still pending.
- If the first call failed, the second is a new attempt and sends its own request. See the retries below.
- the session has ended, through
clearSession()or Portal invalidating it, - another sign-in has completed in this page, or
- the page has reloaded, or the call comes from another tab.
getMagicLinkDetails() and confirmMagicLink() reject with
AuthErrorId.GrantRejected, and a Google or Apple callback fails with
AuthErrorId.OAuthFlowNotStarted, or, if another Google or Apple sign-in has
started in this tab since, with Portal’s 401, which carries no id. If the
first call signed the user in, the session is still stored unless the user has
signed out since, so restoreSession() finds it. That is why the example puts
the address bar back to your redirect URL, without the grant, as soon as the
sign-in completes or is cancelled. A reload after that finds no sign-in result,
and the example says so.
A failed completion is never remembered: the error reaches your page 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. Whether Portal accepts the
retry depends on the first attempt: Portal uses up a grant early while
processing it, before it creates the session. A retry can succeed only if the
first attempt failed before that point, typically because it never reached
Portal. Otherwise the retry is refused: with AuthErrorId.GrantRejected for a
magic link, and with Portal’s 401, which carries no id, for Google or
Apple. 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 callback completed every magic link as soon as it loaded, 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. A callback 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 own page, that the email address is theirs.
AuthErrorId.GrantRejected, the
route keeps the confirmation on screen so the user can try again. The retry can
succeed only if the failed attempt didn’t get as far as using up the link,
typically because it never reached Portal, and otherwise rejects with
AuthErrorId.GrantRejected.
Other failures, such as a rate limit, a server error or a dropped connection,
reach your page unchanged and carry no
id. getMagicLinkDetails() is rate
limited for each link, so don’t poll it: call it once per callback, and again
only when the user asks. Both methods reject 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 a Google or Apple callback 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 the remembered result
with completeOAuthLogin() and confirmMagicLink(), but
a magic link Portal refuses still rejects as it always has here: with Portal’s
401 error, which carries no id, rather than with
AuthErrorId.GrantRejected.
parseRedirect() is stricter than handleRedirect() in three cases that
handleRedirect() keeps for compatibility:
- Without
clientAuth.redirectUrl,parseRedirect()throws, whilehandleRedirect()accepts a callback to any URL. - For a URL carrying both
login_typeandauthMethod,parseRedirect()returnsnull, whilehandleRedirect()completes it as Google or Apple whenlogin_typenames one. - For a Google or Apple callback longer than 8192 characters,
parseRedirect()returnsnull, whilehandleRedirect()still completes it.
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.
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.
Rendering the QR code is your app’s job; Portal does not ship a QR component.
Any library works —
qrcode.react is used above — and challenge.totpLink
should be passed verbatim.@portal-hq/web 5.0.0, the TOTP step stays inside the Portal iframe,
together with the token that authorizes it: challenge.userJwt is always
absent, and verifyTotp() takes only the code. The step lives in the iframe’s
memory, so it doesn’t survive a reload; after one, start a new sign-in. A failed
verifyTotp() that Portal or the iframe refused carries one of these ids. Any
other failure, such as a server error or a dropped connection, carries no id
and usually leaves the step pending, so the user can submit a code again. A code
Portal accepted spends the step even if the sign-in then can’t complete, for
example when the iframe can’t save the session: the next call rejects with
TotpErrorId.ChallengeNotFound.
verifyTotp(code, userJwt) from earlier versions still compiles, but the
second argument is ignored, and passing a value logs a warning once when your
logLevel shows warnings. Code that stores challenge.userJwt as
a string no longer compiles: its type is now undefined.Restore the session
restoreSession() asks the iframe whether it still holds a stored session for
this auth environment. The SDK never calls it for you.
Its result is authoritative in the same way the redirect result is, so hand it
to the same adopt path:
Sign out
onAuthenticationRequired handler fires again and clears the signed-in state
you set with adopt.
clearSession() also cancels a Google or Apple sign-in in progress in this
tab: a callback for that sign-in that completeOAuthLogin() or
handleRedirect() completes afterwards fails with
AuthErrorId.OAuthFlowNotStarted. If your app clears the session as part of
starting a sign-in, call it before getAuthorizeUrl(), not after. Calling it
once the URL has returned abandons that sign-in, and also signs out any current
session, so do that only on purpose. Don’t call it on your callback route
before the callback has completed.
If you call clearSession() while completeOAuthLogin(),
confirmMagicLink() or handleRedirect() is still waiting for Portal, the
Portal iframe finishes that completion first. It resolves as usual, and
clearSession() then ends the session it created, so the user ends up signed
out either way. Your onAuthenticationRequired handler fires after the
completion’s result, so the pattern in
Handle the unauthenticated first state
ends signed out too.
There is no server-side revoke endpoint, so this is a local sign-out; the token
stays valid until the backend expires it.
clearSession() deliberately does not
fire onSessionInvalidated — you already know about a sign-out you asked for.
See API Keys
for session lifetimes.5.0.0, clearSession() also
ends the Google Drive session held by the Portal iframe, so the next backup or
recovery asks the user to choose a Google account. See
Google sign-in and sessions.
Signing out does not delete 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 session with a401, it ended somewhere your app
cannot see and the user has to sign in again. The subscription belongs in
SignedInUserProvider from
Handle the unauthenticated first state,
which is where the example above puts it.
As with a sign-out, an invalidated session does not delete the wallet’s signing
shares — only the credential is gone. Wallet state queries cannot be answered
without a session, so treat them as unknown until the user signs in again rather
than as evidence the wallet is missing.
Handle errors
Credential failures are normalized toPortalCredentialError. Branch on its
reason.
PortalCredentialError. The failures you need to
tell apart carry an id; compare it with AuthErrorId:
Any other failure carries no
id: a Google or Apple grant Portal refuses (a
401), including a callback for a sign-in this tab has since replaced; a magic
link refused through handleRedirect(); a storage failure; a rate limit; a
server error; or a dropped connection. Report it as a failed sign-in. For the
failure cases every SDK shares, see
When a sign-in fails.
PortalAuthPopupError, which you will not encounter using
the redirect flow above.
The Web and React Native Client Auth APIs are not the same shape — different
entry point, different sign-out, and a different
restoreSession() return type.
Do not port code between them; use each platform’s guide.