Skip to content

Instantly share code, notes, and snippets.

@jahe
Last active March 21, 2021 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jahe/66474b82420e5edc521a3ec1a10949e2 to your computer and use it in GitHub Desktop.
Save jahe/66474b82420e5edc521a3ec1a10949e2 to your computer and use it in GitHub Desktop.
Web Application - Best Practices

1. Security

1.1 Clickjacking Attacks

References:

What is Clickjacking?

Attacker's website contains an iframe with your site in it which sits on top of the attacker's website but invisible to the user (opacity: 0). The user then unknowingly interacts with your website and might click a like or purchase button.

Defenses

There are client and server-side defense techniques. Some might not be supported by the users browser so it's best to have them all in place.

Client-side

Use a technique called frame-busting. It replaces the attacker's page with your page.

Keep in mind that this technique can be neutralized by some browsers, browser add-ons or the attackers website itself by blocking the reload.

<!-- index.html -->

<!DOCTYPE html>
<html>
  <head>
    <script>
      if (top != window) {
        top.location = window.location;
      }
    </script>
  </head>

  <!-- ...existing markup... -->

</html>

top returns a reference to the topmost window in the window hierarchy https://developer.mozilla.org/en-US/docs/Web/API/Window/top

Server-side

Using the X-Frame-Options Header

It asks the browser to block any attempt to load your page within an iframe.

Keep in mind that this header has never been standardized although all major browsers are supporting it.

Response Headers

X-Frame-Options: sameorigin

sameorigin tells the browser that only pages of your website can embed it within an iframe. deny is an alternative value that prevents any attempt to put the page within an iframe.

Using CSP

This acts just like the X-Frame-Options header and prevents any attempt to load your page within an iframe.

Response Headers

Content-Security-Policy: frame-ancestors 'self';

This CSP directive allows you to get the same result as the X-Frame-Options header with the sameorigin value.

frame-ancestors 'none'; is an alternative value that prevents any attempt to include the page within a frame. frame-ancestors https://www.your-website.com; is an alternative value that allows you to specify which website is allowed to embed the page in a frame.

Keep in mind that X-Frame-Options takes priority if both headers are specified.

Using cookie's sameSite origin

This approach tells the browser not to send (session) cookies when the request comes from a different domain.

Response Headers

Set-Cookie: my_session=123; SameSite=Strict

Keep in mind that the sameSite property has been recently introduced, so old browsers may not support it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment