ServiceNowFrontend DeveloperAuthentication & Authorization

A ServiceNow frontend application handles sensitive user data. How would a frontend developer design and implement a secure authentication and authorization strategy, considering token management and common vulnerabilities?

ServiceNow Frontend Developer 3–5 Years Authentication & Authorization

6 min readUpdated

A secure frontend authentication strategy involves a robust token management system, typically using JSON Web Tokens (JWTs), combined with defense-in-depth principles against common web vulnerabilities. For sensitive applications, a common and secure pattern involves using a short-lived access token for API calls and a long-lived refresh token for renewing the access token. The key is to manage where these tokens are stored and how they are used to minimize exposure to attacks like Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF).

Token Management Strategy

The access token, being short-lived (e.g., 5-15 minutes), should be stored in memory. This reduces its attack surface significantly because an XSS attack would only grant access for a brief period, and the token is lost on page refresh or browser close. The refresh token, which is used to obtain new access tokens, must be stored more securely. It should be placed in an HTTP-only, secure, and same-site cookie. HTTP-only prevents JavaScript access, mitigating XSS, while secure ensures it’s only sent over HTTPS. Same-site prevents CSRF by limiting cookie sending to same-site requests.

Best practice

Beyond secure token storage, implementing a CSRF synchronization token (double-submit cookie or stateless token) on the frontend for state-changing requests, along with strict Content Security Policy (CSP) headers, is a best practice. The CSP limits which resources (scripts, styles, etc.) the browser is allowed to load, effectively preventing XSS attacks by blocking malicious script injection. Always sanitize user-generated content before rendering to prevent injection vulnerabilities.

Edge case interviewers probe for

Interviewers often ask about silent token refresh. This involves using an iframe or a hidden request to the authentication server to automatically renew the access token using the refresh token before it expires, without requiring the user to re-authenticate or experience a page reload. This provides a seamless user experience while maintaining the security benefits of short-lived access tokens. Additionally, robust server-side refresh token invalidation on logout or suspicion of compromise is crucial.

Common mistake

A very common and critical mistake is storing access tokens (or even refresh tokens) in browser localStorage. While convenient, localStorage is accessible via JavaScript, making it highly vulnerable to XSS attacks. If an attacker manages to inject malicious script, they can easily steal tokens from localStorage, gaining unauthorized access to the user’s account without needing their credentials.

What the interviewer is checking

The interviewer is assessing your understanding of fundamental web security principles, particularly in the context of single-page applications. They want to see if you can articulate a secure token management strategy, identify common vulnerabilities like XSS and CSRF, and describe practical mitigation techniques. Your ability to balance security with user experience, such as through silent refresh, is also being evaluated.

Imagine you are going to an exclusive nightclub. When you first arrive, a bouncer (the login server) checks your ID (username and password). If you’re approved, they give you two things: a temporary wristband (your access token), which lets you walk right in for the next 15 minutes, and a special VIP card (your refresh token) that you promise to keep super safe. The wristband is for quick entry to the dance floor (the API server) without showing your ID every time.

You wear the wristband (access token) in your pocket, ready for quick display, but you tuck the VIP card (refresh token) deep in a secure, hidden pouch (an http-only, secure cookie) that only the bouncer can touch, and you can’t even see it. If your wristband’s time runs out, you secretly show your VIP card to the bouncer (the authentication service) and they give you a new wristband, so you never miss a beat on the dance floor. If you leave the club, you make sure to tell the bouncer to shred your VIP card so no one else can sneak in with it.

Why interviewers ask this

Interviewers ask this to gauge your security awareness in frontend development, your understanding of token-based authentication, and your ability to design resilient systems that protect user data against common web threats.

What a strong answer signals

A strong answer demonstrates practical knowledge of modern authentication flows, secure token storage best practices, and a proactive approach to mitigating XSS and CSRF vulnerabilities, showing you can build secure frontend applications.

Common follow-ups

  • How would you implement CSRF protection with tokens in a single-page application?
  • What are the pros and cons of using http-only cookies versus web storage for tokens?
  • Describe the process of a silent token refresh, including the role of iframes.

Advanced variation

Design an authentication system for a multi-tenant application where each tenant might have different identity providers (e.g., SAML, OAuth), and the frontend needs to securely handle various authentication mechanisms transparently to the user.

Consider a banking Single Page Application (SPA) where an initial implementation stored both access and refresh tokens in localStorage. After a security audit revealed high XSS vulnerability, the team refactored the authentication flow. They moved the short-lived access token to an in-memory variable, accessible only by the application’s runtime JavaScript. The long-lived refresh token was migrated to an HTTP-only, secure, and SameSite cookie, ensuring it could not be accessed by client-side scripts and was protected against CSRF attacks, significantly hardening the application’s security posture without disrupting the user experience through a silent refresh mechanism.

auth-fetch-wrapper.js
// Simplified functions for token management (implementation details omitted)
let inMemoryAccessToken = null;
const getAccessTokenFromMemory = () => inMemoryAccessToken;
const saveAccessTokenToMemory = (token) => { inMemoryAccessToken = token; // Also set expiration timer };
const isTokenExpired = (token) => { // Check JWT expiry timestamp return false; }; // Placeholder

async function fetchWithAuth(url, options = {}) {
  let accessToken = getAccessTokenFromMemory();
  if (!accessToken || isTokenExpired(accessToken)) {
    // Attempt silent refresh using http-only cookie (credentials: 'include')
    try {
      const response = await fetch('/api/auth/refresh', { method: 'POST', credentials: 'include' });
      if (!response.ok) throw new Error('Failed to refresh token');
      const data = await response.json();
      accessToken = data.accessToken;
      saveAccessTokenToMemory(accessToken);
    } catch (error) {
      // Refresh failed, likely refresh token expired or revoked. Force re-login.
      console.error('Authentication refresh failed:', error);
      window.location.href = '/login'; // Redirect to login page
      return Promise.reject(new Error('Authentication required'));
    }
  }
  // Attach the valid access token to the request headers
  options.headers = {
    ...options.headers,
    'Authorization': `Bearer ${accessToken}`,
  };
  return fetch(url, options);
}

// Example usage:
// fetchWithAuth('/api/protected-data')
//   .then(response => response.json())
//   .then(data => console.log(data))
//   .catch(error => console.error('Failed to fetch data:', error));
Client (Browser) Access Token (Memory) Refresh Token (HttpOnly Cookie) Backend API Authentication Service API Call (with Access Token) Refresh Request (with Refresh Token) New Access Token
  1. 1JWTs are stateless, but their secure handling on the frontend is crucial for application security.
  2. 2Store short-lived access tokens in memory and long-lived refresh tokens in http-only, secure, SameSite cookies.
  3. 3Implement a silent token refresh mechanism to renew access tokens seamlessly for an uninterrupted user experience.
  4. 4CSRF tokens, robust XSS prevention (e.g., CSP), and input sanitization are essential layered defenses for frontend applications.
  5. 5Always ensure server-side refresh token invalidation on explicit logout or detection of compromise.