Anti CSRF
#
What is a CSRF AttackCSRF 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.
sameSite
cookie attribute#
Relation with 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-csrfcaution
- 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:
- NodeJS
- GoLang
- Python
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"
})
]
});
import (
"github.com/supertokens/supertokens-golang/recipe/session"
"github.com/supertokens/supertokens-golang/recipe/session/sessmodels"
"github.com/supertokens/supertokens-golang/supertokens"
)
func main() {
// Should be one of "NONE" or "VIA_CUSTOM_HEADER" or "VIA_TOKEN"
antiCsrf := "VIA_CUSTOM_HEADER"
supertokens.Init(supertokens.TypeInput{
RecipeList: []supertokens.Recipe{
session.Init(&sessmodels.TypeInput{
AntiCsrf: &antiCsrf,
}),
},
})
}
from supertokens_python import init, InputAppInfo
from supertokens_python.recipe import session
init(
app_info=InputAppInfo(api_domain="...", app_name="...", website_domain="..."),
framework='...',
recipe_list=[
session.init(
# Should be one of "NONE" or "VIA_CUSTOM_HEADER" or "VIA_TOKEN"
anti_csrf='VIA_CUSTOM_HEADER'
)
]
)
- 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 ifsameSite
isnone
or if yourapiDomain
andwebsiteDomain
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 aniframe
.