Making sure your web application cannot be framed by another website is one way to stop clickjacking, often referred to as UI redressing, which allows attackers to fool users into clicking on something different from what they actually see.
1. X-Frame-Options (XFO) HTTP Header
The most straightforward way to prevent clickjacking is by setting the X-Frame-Options HTTP header. This header instructs the browser whether your page can be iframed or not.
- DENY: Page cannot be iframed by any site.
- SAMEORIGIN: Page can only be iframed by the same origin (domain, protocol, and port).
- ALLOW-FROM https://example.com/: Page can only be iframed by the specified origin. Note: This is less commonly used due to browser support issues (not supported in Chrome or Firefox, for example).
Implementation:
# To deny all
Header always set X-Frame-Options "DENY"
# To allow from the same origin
Header always set X-Frame-Options "SAMEORIGIN"
2. Content-Security-Policy (CSP) frame-ancestors Directive
While primarily used for defining which sources of content are allowed to be executed within a web page, CSP's frame-ancestors directive can also be used to mitigate clickjacking by specifying which parents are allowed to frame your page.
- 'none': No page can frame the content.
- 'self': The page can only be framed by the same origin.
- https://example.com: Specifies a domain that can frame the content.
Implementation:
# To deny all
Header always set Content-Security-Policy "frame-ancestors 'none';"
# To allow from the same origin
Header always set Content-Security-Policy "frame-ancestors 'self';"
# To allow from a specific domain
Header always set Content-Security-Policy "frame-ancestors https://example.com;"
Browser Compatibility Considerations:
1. X-Frame-Options:
- Supported by most modern browsers, including Chrome, Firefox, Edge, Safari, and Opera.
- Partial Support in older browsers (e.g., IE11 supports only DENY and SAMEORIGIN).
2. Content-Security-Policy (frame-ancestors):
- Supported in modern browsers (Chrome, Firefox, Edge, Safari, Opera).
- Limited or No Support in older browsers (e.g., IE11 does not support frame-ancestors).