HIGH clickjackingrestifybearer tokens

Clickjacking in Restify with Bearer Tokens

Clickjacking in Restify with Bearer Tokens — how this specific combination creates or exposes the vulnerability

Clickjacking is a client-side UI redress attack where an attacker tricks a user into interacting with a hidden or disguised element inside an invisible or embedded frame. In a Restify service that uses Bearer Tokens for authentication, the combination of token-based auth and missing frame protections can amplify the impact of clickjacking. Because Restify APIs commonly serve JSON to web clients, a frontend that consumes these APIs may render responses in iframes or embed third-party assets without proper framing controls. If an endpoint validates only the Bearer Token presence and not the request origin, a malicious page can embed the trusted API route in a frame and drive user actions (e.g., changing settings or transferring funds) via CSRF-like interactions.

When a Bearer Token is stored in browser-accessible storage (such as localStorage) and used in the Authorization header, JavaScript on a compromised page can read the token if cross-origin isolation is not enforced. An attacker can then combine token exfiltration techniques with clickjacking to both authenticate as the victim and drive unauthorized UI actions. For example, an endpoint like DELETE /account/reset that requires a Bearer Token but lacks anti-CSRF measures and frame-ancestors policy may be invoked programmatically via an invisible form or iframe. The browser will include the token automatically if it is attached to requests by an authenticated client (e.g., via an Authorization header), enabling the attacker to perform actions on behalf of the user.

Moreover, if the Restify API serves HTML or renders views that include inline scripts or iframes without Content-Security-Policy (CSP) frame-ancestors restrictions, it becomes easier for an attacker to overlay invisible controls. The API might return user-specific data intended for a legitimate client, but without proper sandboxing, that data can be captured inside a clickjacked context. Because middleBrick tests include Input Validation and checks related to unsafe consumption patterns, it can surface endpoints that accept credentials (like Bearer Tokens) but do not enforce strict origin checks or anti-clickjacking headers. This highlights the need to treat Bearer Tokens as sensitive as cookies and to apply defense-in-depth by layering token security with framing and CSP rules.

Bearer Tokens-Specific Remediation in Restify — concrete code fixes

To mitigate clickjacking risks when using Bearer Tokens in Restify, apply both server-side header protections and secure coding patterns. First, enforce a strict Content-Security-Policy with frame-ancestors to prevent your API responses from being embedded. Second, avoid storing Bearer Tokens in locations accessible to potentially malicious third-party scripts, and prefer same-site and secure cookie attributes for session-bound tokens where applicable. Finally, require explicit origin or referer checks for state-changing methods and implement anti-CSRF tokens for operations that are not idempotent or that modify sensitive state.

Example: Setting security headers in a Restify server to prevent framing and limit token exposure:

const restify = require('restify');
const server = restify.createServer();

server.use((req, res, next) => {
  // Prevent embedding in frames
  res.setHeader('Content-Security-Policy', "frame-ancestors 'none'");
  // Recommend strict transport and token handling in production
  res.setHeader('Strict-Transport-Security', 'max-age=15552000; includeSubDomains');
  next();
});

server.get('/profile', (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return next(new restify.UnauthorizedError('Missing Authorization'));
  // Validate token with your auth provider here
  res.send({ message: 'Profile data' });
  return next();
});

server.listen(8080, () => console.log('Listening on 8080'));

Example: Implementing origin checks and anti-CSRF tokens for state-changing routes:

const csrf = require('csurf');
const cookieParser = require('cookie-parser');
const restify = require('restify');
const server = restify.createServer();

server.use(cookieParser());
const csrfProtection = csrf({ cookie: true });

// Apply CSRF protection only to endpoints that require it (e.g., POST/PUT/DELETE)
server.post('/transfer', csrfProtection, (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  const origin = req.headers.origin;
  const allowedOrigins = ['https://trusted-app.example.com'];
  if (!allowedOrigins.includes(origin)) {
    return next(new restify.ForbiddenError('Invalid Origin'));
  }
  if (!req.csrfToken()) return next(new restify.InternalServerError('CSRF setup error'));
  // Ensure the client sends the CSRF token in header or body
  const clientToken = req.headers['x-csrf-token'] || req.body._csrf;
  if (clientToken !== req.csrfToken()) {
    return next(new restify.ForbiddenError('Invalid CSRF Token'));
  }
  // Proceed with authenticated and origin-validated action
  res.send({ status: 'ok' });
  return next();
});

These patterns ensure that even if a Bearer Token is present and valid, the endpoint will reject requests that do not originate from trusted sources and that lack valid CSRF protection. By combining CSP frame-ancestors, strict origin validation, and CSRF tokens, you reduce the attack surface for clickjacking against Restify services that rely on token-based authentication.

Frequently Asked Questions

Can an API-only Restify service be clickjacked if it never returns HTML?
Yes. Clickjacking can still affect API-driven flows when a browser-based client embeds your API calls inside frames or iframes. Even if the API itself returns JSON, attackers can drive UI actions in a malicious page by leveraging authenticated requests that include Bearer Tokens. Protections like CSP frame-ancestors, secure token storage, and CSRF tokens remain essential.
Is storing Bearer Tokens in Authorization headers safe from clickjacking if I use HTTPS?
HTTPS protects token confidentiality in transit but does not prevent clickjacking. A malicious site can still make authenticated requests if the user’s session includes valid tokens (e.g., stored in localStorage or injected via scripts). Defense-in-depth with CSP frame-ancestors, strict origin checks, and CSRF mitigation is required to reduce risk.