MediumAuthentication📖 Theory Question

How would you implement silent token refresh in a SPA?

💡

Hint

Use a hidden iframe to hit the IdP (if SSO session exists) or an in-memory refresh token to get a new access token before expiry

Full Answer

Access tokens expire (typically 15 min). Silent refresh keeps users logged in without forcing them to re-authenticate.

Option 1: Hidden iframe (OIDC prompt=none)

// When access token is near expiry, load IdP in hidden iframe
const iframe = document.createElement('iframe');
iframe.src = `${idpUrl}/authorize?prompt=none&response_type=code&...`;
iframe.style.display = 'none';
document.body.appendChild(iframe);
// Listen for redirect back to /silent-callback
// Parse new token from callback URL

Works if the user still has an active SSO session with the IdP. Requires prompt=none OIDC parameter. Blocked by Safari ITP (third-party cookie restrictions).

Option 2: Refresh token in HttpOnly cookie

// Before request, check token expiry
async function getAccessToken() {
  if (isExpiringSoon(accessToken)) {
    const { data } = await axios.post('/auth/refresh'); // sends HttpOnly cookie automatically
    accessToken = data.accessToken; // store in memory only
  }
  return accessToken;
}

Keep the access token in memory (not localStorage) to prevent XSS theft. The refresh token in HttpOnly cookie is safe from JavaScript. This is the recommended modern approach.

More Authentication Questions

EasyWhat are the security differences between storing a JWT in localStorage vs an HttpOnly cookie?EasyWhat is refresh token rotation and why is it important?EasyWhat is OAuth 2.0 PKCE and when should you use it?EasyWhat is the difference between authentication and authorization?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint