MEDIUM clickjackingsailsbearer tokens

Clickjacking in Sails with Bearer Tokens

Clickjacking in Sails 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 iframe. In Sails.js, if an application embeds its own pages in frames without explicit frame-busting or anti-clickjacking headers, and also relies on Bearer Tokens for authorization, the combination can amplify risk for certain workflows.

Bearer Tokens are typically stored in browser-side JavaScript (e.g., in a SPA) or passed via the Authorization header. When a Sails app embeds views in iframes and uses token-based auth, an attacker may craft a malicious page that loads the Sails endpoint in a hidden iframe. If the endpoint does not enforce Content-Security-Policy: frame-ancestors or X-Frame-Options, the iframe loads successfully. Because the browser automatically includes cookies and may attach Authorization headers (e.g., via JavaScript fetching the token from storage and using it in requests), the embedded view may perform privileged actions on behalf of the authenticated user without their explicit consent.

For example, consider a Sails endpoint that allows changing the user’s email via a POST request and relies on a Bearer Token passed in an Authorization header. If an attacker’s page calls this endpoint from a hidden iframe using JavaScript, and the browser includes the token automatically (via application logic), the action may succeed. This is particularly relevant when the Sails API is consumed by a frontend framework that attaches the Authorization header programmatically and embeds admin pages in iframes for integration or preview features.

In such scenarios, the API security checks provided by middleBrick can help detect missing frame-ancestors policies or other misconfigurations. By scanning the unauthenticated attack surface, middleBrick identifies whether responses include appropriate CSP headers or X-Frame-Options values. Note that middleBrick does not fix, patch, block, or remediate; it provides findings with remediation guidance to help you address exposure vectors like this.

To validate the presence of clickjacking risks in a Sails API, you can use middleBrick’s Web Dashboard or CLI to scan endpoints that return sensitive views or admin panels. The scanner checks for missing frame-ancestors directives and other headers that mitigate clickjacking, helping you understand whether an authenticated action surface is exposed when Bearer Tokens are used for authorization.

Bearer Tokens-Specific Remediation in Sails — concrete code fixes

Remediation focuses on preventing the Sails app from being embedded in hostile frames and ensuring Bearer Token usage does not enable unauthorized actions via clickjacking vectors. Below are concrete steps and code examples for a Sails application.

1. Set HTTP response headers to prevent framing. In your Sails config (e.g., config/http.js), add middleware that sets security headers:

// config/http.js
module.exports.http = {
  middleware: {
    order: ['startRequestTimer', 'cookieParser', 'session', 'bodyParser', 'securityHeaders', 'router'],
    securityHeaders: function (req, res, next) {
      // Prevent embedding in iframes
      res.set('X-Frame-Options', 'DENY');
      // Modern alternative: restrict frame origins
      res.set('Content-Security-Policy', "frame-ancestors 'self' https://trusted.example.com;");
      return next();
    }
  }
};

2. Ensure Bearer Token handling does not leak into insecure contexts. When using tokens in a frontend SPA, avoid storing tokens in ways that automatically attach to cross-origin requests initiated by embedded pages. Instead, require explicit user interaction for sensitive actions and validate the Origin or Referer headers on the server. In Sails, you can validate origins in a policy:

// api/policies/validateOrigin.js
module.exports = function (req, res, next) {
  const allowedOrigins = ['https://app.example.com', 'https://admin.example.com'];
  const origin = req.headers.origin;
  if (!origin || allowedOrigins.indexOf(origin) === -1) {
    return res.forbidden('Origin not allowed');
  }
  return next();
};

Apply this policy to sensitive actions in config/policies.js:

// config/policies.js
module.exports.policies = {
  UserController: {
    changeEmail: ['validateOrigin'],
    updateProfile: ['validateOrigin']
  }
};

3. When consuming APIs from a frontend, explicitly set the Authorization header instead of relying on cookies. Here is an example using fetch with a Bearer Token, ensuring the request is not inadvertently triggered from an embedded context:

// Example frontend request (e.g., in your SPA)
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
fetch('https://api.example.com/user/change-email', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer ' + token,
    'Content-Type': 'application/json',
    'Origin': 'https://app.example.com' // explicit origin for server-side checks
  },
  body: JSON.stringify({ email: '[email protected]' })
}).then(response => {
  if (!response.ok) throw new Error('Request failed');
  return response.json();
}).then(data => console.log(data)).catch(err => console.error(err));

4. For Sails APIs that serve both browser clients and programmatic consumers, differentiate behavior based on the presence and usage of the Authorization header. Do not rely solely on the presence of a token to authorize an action if the request originates from an untrusted frame. Combine token validation with CSRF-safe patterns for state-changing operations, even if you primarily use Bearer Tokens.

These measures reduce the attack surface when using Bearer Tokens in Sails. Remember that middleBrick scans can surface missing security headers and provide prioritized findings with remediation guidance, helping you verify that your configuration aligns with recommended practices.

Frequently Asked Questions

Does middleBrick fix clickjacking misconfigurations in Sails apps?
No. middleBrick detects and reports misconfigurations, such as missing X-Frame-Options or Content-Security-Policy frame-ancestors, that may enable clickjacking. It provides remediation guidance but does not fix, patch, block, or remediate.
Can Bearer Tokens alone prevent clickjacking in Sails?
Bearer Tokens handle authentication but do not prevent clickjacking. You must also enforce anti-framing headers (X-Frame-Options or Content-Security-Policy frame-ancestors) and apply server-side origin validation to mitigate clickjacking risks.