Single Sign-On and identity management built for developers, organizations, and enterprises. Explore documentation →
Logo

Keeping Angular and Vue SPAs Logged In After Third-Party Cookie Deprecation

How to replace broken hidden-iframe silent renewal with PKCE rotating refresh tokens, single-flight HTTP interceptors, and first-party custom auth domains.

DR
SSO.ID Developer Relations
Protocol & SDK Engineering · 2026-11-05 · 9 min read
LinkedIn Share
Why This Matters Right Now

For nearly a decade, Angular and Vue SPAs refreshed expired access tokens silently using a hidden iframe pointing to /oauth/authorize?prompt=none. Safari ITP, Firefox Total Cookie Protection, Brave Shields, and Chrome's third-party cookie restrictions now block cross-site IdP session cookies inside those iframes—causing silent login_required failures that randomly kick users out mid-workflow every 15 to 60 minutes.

Key Takeaways

  • Hidden-iframe silent renewal fails whenever your SPA domain (app.company.com) and Identity Provider domain (auth.idp.com) are cross-site and the browser strips third-party cookies.
  • Migrating SPAs to Authorization Code + PKCE S256 with rotating refresh tokens (offline_access) uses direct CORS POST /oauth/token requests that require zero third-party cookies.
  • Hosting your IdP on a first-party custom domain (auth.company.com alongside app.company.com) restores same-site cookie posture for cross-app silent SSO.
  • Angular HttpInterceptors and Vue/Axios interceptors must queue concurrent 401 responses behind a single in-flight refresh stream to avoid colliding on rotating refresh tokens.

Why Hidden-Iframe Silent Renewal Breaks in Modern Browsers

Classic OIDC SPA libraries relied on an invisible <iframe> to send GET /oauth/authorize?prompt=none&response_type=code to the authorization server. That trick depended entirely on the browser attaching the IdP's authentication cookie (set on auth.idp.com) from inside an embedded frame hosted on app.yourcompany.com. Because the top-level document and the iframe do not share the same eTLD+1 site, every modern privacy-hardened browser classifies that IdP cookie as a third-party tracker.

Safari Intelligent Tracking Prevention (ITP) and Firefox Total Cookie Protection partition or drop cross-site cookies by default, and enterprise Chrome policies increasingly block unpartitioned third-party cookies. When the cookie is stripped, the IdP sees an anonymous iframe request and immediately redirects back with error=login_required. Users editing long forms in an Angular enterprise portal or Vue SaaS dashboard suddenly hit unexpected full-page login redirects—losing unsaved state and flooding support queues.

  • Third-party cookie blocking affects Safari (macOS and all iOS browsers), Firefox, Brave, Edge Strict Mode, and Chrome Incognito/privacy-restricted profiles.
  • Iframe timeouts (X-Frame-Options, CSP frame-ancestors, or corporate proxy latency) create flaky race conditions that are notoriously hard to reproduce locally.
  • Even when Storage Access API workarounds exist, they require explicit user gesture prompts that defeat the entire goal of silent background renewal.
  • Any SPA architecture designed for 2026 and beyond must treat cross-site iframe cookies as permanently unavailable.

Implementing Single-Flight Refresh Interceptors in Angular and Vue 3

Dashboard views in Angular and Vue routinely mount six or eight widgets simultaneously, firing parallel HTTP requests the instant a user opens a tab after lunch. If the access token expired two minutes earlier, all eight API requests fail with 401 Unauthorized simultaneously. Without single-flight coordination, all eight error handlers invoke refreshToken() in parallel—colliding on a single-use rotating refresh token and triggering reuse-detection revocation.

In modern standalone Angular (16–20), implement a functional HttpInterceptor backed by a shared BehaviorSubject (or RxJS shareReplay(1) observable) so the first 401 kicks off exactly one refresh call while the other seven requests pause via filter() + take(1) and automatically retry with the newly minted Bearer token. In Vue 3 with Axios or ofetch, apply the identical pattern using a module-scoped refreshPromise: concurrent 401 handlers await the existing promise instead of issuing duplicate /oauth/token calls.

  • Guard against infinite 401 retry loops by tagging retried requests (e.g., an HttpContext token or _retried flag) so a genuine 401 from an unauthorized resource fails cleanly.
  • Proactively refresh tokens 60 seconds before exp via a lightweight timer or pre-request check so normal navigation rarely even hits a 401.
  • Clear in-memory state and trigger interactive login immediately if the refresh endpoint itself returns 400 invalid_grant.
  • Exclude auth discovery and token endpoints from Bearer header injection inside your interceptor.
typescript
// Angular 16-20 standalone functional HttpInterceptor with single-flight token refresh
import { HttpInterceptorFn, HttpErrorResponse, HttpContextToken } from "@angular/common/http";
import { inject } from "@angular/core";
import { BehaviorSubject, catchError, filter, switchMap, take, throwError } from "rxjs";
import { SsoIdService } from "@sso-id/angular";

const IS_RETRY = new HttpContextToken<boolean>(() => false);
let refreshInFlight = false;
const refreshedToken$ = new BehaviorSubject<string | null>(null);

export const ssoIdBearerInterceptor: HttpInterceptorFn = (req, next) => {
  const auth = inject(SsoIdService);
  if (req.url.startsWith("https://auth.sso.id")) return next(req);

  const token = auth.getCachedAccessToken();
  const authedReq = token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;

  return next(authedReq).pipe(
    catchError((err: HttpErrorResponse) => {
      if (err.status !== 401 || req.context.get(IS_RETRY)) {
        return throwError(() => err);
      }

      if (!refreshInFlight) {
        refreshInFlight = true;
        refreshedToken$.next(null);
        return auth.refreshAccessToken$().pipe(
          switchMap((newToken) => {
            refreshInFlight = false;
            refreshedToken$.next(newToken);
            const retryReq = req.clone({
              setHeaders: { Authorization: `Bearer ${newToken}` },
              context: req.context.set(IS_RETRY, true)
            });
            return next(retryReq);
          }),
          catchError((refreshErr) => {
            refreshInFlight = false;
            auth.loginWithRedirect();
            return throwError(() => refreshErr);
          })
        );
      }

      return refreshedToken$.pipe(
        filter((t): t is string => t !== null),
        take(1),
        switchMap((newToken) =>
          next(req.clone({
            setHeaders: { Authorization: `Bearer ${newToken}` },
            context: req.context.set(IS_RETRY, true)
          }))
        )
      );
    })
  );
};
Implementation Tip: Handle Vue 3 Router Guards Without Flicker

In Vue 3 with vue-router, await auth.initialize() once inside a global beforeEach navigation guard before evaluating isAuthenticated. Trying to read reactive auth refs synchronously before the initial OIDC callback exchange or startup token refresh settles causes spurious redirect loops back to /oauth/authorize.

Cross-Tab Sync and Preserving User State on Re-Authentication

Eliminating iframe renewal also exposes a subtle multi-tab UX challenge: if a user opens a deep link in a second tab and your SPA keeps tokens strictly in memory, Tab 2 boots with an empty memory cache. Using BroadcastChannel (or a SharedWorker), Tab 2 can request the active in-memory session state from Tab 1 on boot in under 5 milliseconds without ever persisting tokens to localStorage or triggering an unnecessary redirect.

When a session truly hits its absolute lifetime cap or gets revoked by an administrator, prioritize non-destructive UX. Before invoking loginWithRedirect(), serialize the user's current route path, query parameters, and any unsaved draft form state into short-lived sessionStorage keyed by the OAuth state parameter, then restore that exact workspace state cleanly once the callback returns.

  • Coordinate refresh locks across tabs via navigator.locks and propagate fresh access tokens via BroadcastChannel.
  • Propagate LOGOUT events over BroadcastChannel so signing out in one tab immediately clears memory and redirects all sibling tabs.
  • Save returnTo paths (validated as relative same-origin paths to prevent open redirects) inside app state before interactive re-auth.
  • Test renewal explicitly in Safari Private Browsing and Firefox Strict Mode during QA—never validate SPA auth exclusively in standard Chrome.

How SSO.ID Keeps Angular and Vue SPAs Signed In Without Third-Party Cookies

SSO.ID's official Angular, Vue, and SPA JavaScript SDKs use Authorization Code + PKCE S256 with rotating refresh tokens, built-in multi-tab synchronization, and optional custom first-party auth domains.

  • ✓Standalone-ready @sso-id/angular SDK with provideSsoId(), ssoIdAuthGuard, automatic Bearer HttpInterceptor, and RxJS observables for Angular 16–20.
  • ✓Vue 3 Composition API SDK (@sso-id/vue) featuring createSsoId(), reactive useSsoId() composables, and vue-router navigation guards.
  • ✓Framework-agnostic @sso-id/spa-js core with PKCE S256, cookie-free rotating refresh tokens, and built-in multi-tab synchronization.
  • ✓First-party custom domain support (e.g., auth.yourcompany.com) to maintain seamless same-site SSO across all customer-facing subdomains.

Frequently Asked Questions

If my SPA uses rotating refresh tokens without iframes, what happens when the user refreshes the page (F5)?

If tokens are stored strictly in memory and the browser has no first-party IdP cookie, a hard F5 reload clears memory and initiates a fast top-level redirect (or checks a first-party custom domain session). Alternatively, pairing a BFF HttpOnly cookie or a first-party custom auth domain preserves sessions seamlessly across full page reloads.

Does CORS need special configuration on the Identity Provider for SPA token refresh?

Yes. Your SPA's exact origin (for example, https://app.cloudpulse.io) must be registered on your SSO.ID application so POST https://auth.sso.id/oauth/token returns the appropriate Access-Control-Allow-Origin headers for browser PKCE exchanges.

Are Angular and Vue apps using oidc-client-ts compatible with SSO.ID?

Yes. Because SSO.ID exposes standard OIDC Discovery at /.well-known/openid-configuration with PKCE S256 and rotating refresh tokens, standard OIDC clients work out of the box—though @sso-id/angular and @sso-id/vue add Menu RBAC helpers and multi-tab refresh coordination automatically.

Topics: #Angular #Vue 3 #Silent Renewal #Third-Party Cookies