One of the common web security questions that checks browser layout protection knowledge is:

What is a Clickjacking attack, and how do you protect your site from being loaded inside unauthorized iframes?

Clickjacking (UI Redress Attack) is a malicious technique where an attacker tricks a user into clicking on a hidden, transparent element of a trusted webpage that has been embedded inside an iframe on an untrusted page.


1. How Clickjacking Works#

An attacker builds a malicious webpage (e.g. https://attacker-site.com) containing:

  1. An appealing button (e.g., "Win a Free iPhone").
  2. A completely transparent <iframe> (CSS opacity: 0) loading a victim webpage (e.g., https://my-bank.com/transfer) positioned precisely on top of the "Win a Free iPhone" button.

When the user attempts to click "Win a Free iPhone", they are actually clicking the transparent "Submit Transfer" button on the bank page, executing transactions without their knowledge.

 Attacker UI (Visible)            Bank UI (Invisible Frame)
 ┌───────────────────────┐        ┌───────────────────────┐
 │   WIN A FREE IPHONE   │ ◄──────│    SUBMIT TRANSFER    │
 │       [ Click! ]      │        │      [ Click! ]       │
 └───────────────────────┘        └───────────────────────┘

The modern, standard way to block unauthorized iframe embedding is using the Content Security Policy frame-ancestors directive:

  • Block all embedding:
    HTTP
    Content-Security-Policy: frame-ancestors 'none';
    
  • Allow only the same origin:
    HTTP
    Content-Security-Policy: frame-ancestors 'self';
    
  • Allow specific trusted origins:
    HTTP
    Content-Security-Policy: frame-ancestors 'self' https://trusted-partner.com;
    

3. Mitigation #2: X-Frame-Options Header#

For older browsers that do not support CSP level 2, you should also send the legacy X-Frame-Options HTTP header:

  • DENY: The page cannot be displayed in a frame, regardless of the site attempting to do so.
  • SAMEORIGIN: The page can only be displayed in a frame on the same origin as the page itself.
HTTP
X-Frame-Options: SAMEORIGIN

Note

If a webpage sends both Content-Security-Policy with frame-ancestors and X-Frame-Options, modern browsers will prioritize the CSP directive and ignore the legacy header.


Key Takeaways#

  • UI Redress Attack: Clickjacking redresses the user interface using transparent iframes to steal click interactions.
  • frame-ancestors rules: Use CSP frame-ancestors to restrict which domains can frame your application pages.
  • Avoid JS Frame Busting: Legacy JavaScript frame-busting scripts (e.g. checking top !== self) are unreliable and can be bypassed by setting sandbox attributes on the parent iframe.
  • Set Headers Server-Side: Always emit security headers at the web server (e.g. Nginx, Vercel configs) or middleware level to ensure they cover all application paths.