Skip to main content

CSRF

The csrf plugin protects browser-facing routes from cross-site request forgery. In these attacks, another site causes a user's browser to send an authenticated request that the user did not intend. The plugin requires state-changing requests to prove that they came from the client that received its signed token.

Examples​

The examples show how the gateway rejects an unsafe request without a token and accepts one that submits the same signed token in the request header and cookie.

Reject an Unsafe Request Without a Token​

Configure a route that requires a signed CSRF token for requests that can change state.

Create the route:

curl "http://127.0.0.1:9180/apisix/admin/routes/csrf-doc-route" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"uri": "/anything/csrf-doc",
"plugins": {
"csrf": {
"key": "docs-csrf-secret-8f3d7c2a1b9e"
}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"httpbin.org:80": 1
}
}
}'

The example signing key is only for local testing. Use a high-entropy secret in production.

The gateway adds a fresh signed token cookie to every response. Requests using methods other than GET, HEAD, and OPTIONS must return the same token in the configured request header and cookie. The token signature must be valid and, when token-age validation is enabled, within the configured validity period. Missing or mismatched tokens return 401 Unauthorized without contacting the upstream.

The gateway does not validate tokens for GET, HEAD, or OPTIONS. Do not use these methods for operations that change state.

Send a POST request without a token:

curl --include "http://127.0.0.1:9080/anything/csrf-doc" -X POST

The gateway rejects the request before it reaches the upstream:

HTTP/1.1 401 Unauthorized
...
{"error_msg":"no csrf token in headers"}

Submit a Matching Token​

Send a safe request to obtain a signed token cookie, then read the token from the cookie jar:

curl "http://127.0.0.1:9080/anything/csrf-doc" \
--silent \
--show-error \
--fail \
--cookie-jar cookies.txt \
--output /dev/null

CSRF_TOKEN=$(awk '$6 == "apisix-csrf-token" {print $7}' cookies.txt)

if [ -z "$CSRF_TOKEN" ]; then
echo "CSRF token was not returned"
exit 1
fi

Submit the token in the request header while sending the cookie from the jar:

curl "http://127.0.0.1:9080/anything/csrf-doc" -X POST \
-H "apisix-csrf-token: ${CSRF_TOKEN}" \
--cookie cookies.txt \
--silent \
--show-error \
--fail \
--output /dev/null \
--write-out "Allowed response: %{http_code}\n"

The matching token passes validation and the request reaches the upstream:

Allowed response: 200