Skip to main content

Anti CSRF

What is a CSRF Attack#

CSRF attacks can happen if a logged in user visits a malicious website which makes an API call to your website's API to maliciously change that user's data.

To protect against this attack, we use the cookie sameSite attribute along with some anti-csrf measures.

Relation with sameSite cookie attribute#

The sameSite cookie attribute is used to declare if your cookies should be restricted to a first-party or same-site context. Properly configuring sameSite can prevent CSRF attacks.

For example, if sameSite is lax, the browser will only send cookies for requests that originate from the same top level domain as the API's domain. So if a user visits a malicious site, requests from those sites will not have the session cookies.

Manually enable anti-csrf#

caution
  • SuperTokens automatically defends against CSRF attacks.
  • Please only change this setting if you know what you are doing. If you are unsure, please feel free to ask questions to us.
  • This setting is ignored while using header-based authentication, since they get the same protection as antiCsrf set to VIA_CUSTOM_HEADER.

You can manually set the antiCsrf config option to take control of the kind of CSRF protection you get:

import SuperTokens from "supertokens-node";
import Session from "supertokens-node/recipe/session";

SuperTokens.init({
supertokens: {
connectionURI: "...",
},
appInfo: {
apiDomain: "...",
appName: "...",
websiteDomain: "..."
},
recipeList: [
Session.init({
antiCsrf: "VIA_CUSTOM_HEADER", // Should be one of "NONE" or "VIA_CUSTOM_HEADER" or "VIA_TOKEN"
})
]
});
  • A value of "NONE" would disable any anti-csrf protection from our end. You can use this if you have your own implementation of CSRF protection.
  • A value of "VIA_CUSTOM_HEADER" uses this method to prevent CSRF protection. This is set automatically if sameSite is none or if your apiDomain and websiteDomain do not share the same top level domain name.
  • A value of "VIA_TOKEN" uses an explicit anti-csrf token. Use this method if you want to allow any origin to query your APIs. This method may cause issues in browsers like Safari, especially if your site is embedded as an iframe.
Which frontend SDK do you use?
supertokens-web-js / mobile
supertokens-auth-react