# 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[​](#examples "Direct link to 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[​](#reject-an-unsafe-request-without-a-token "Direct link to Reject an Unsafe Request Without a Token")

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

* Admin API
* ADC
* Ingress Controller

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

      }

    }

  }'
```

Configure ADC to connect to the target backend. The remaining ADC commands read the connection settings from these environment variables:

* APISIX
* API7 Gateway

```
export ADC_BACKEND=apisix

export ADC_SERVER="http://127.0.0.1:9180"

export ADC_TOKEN="${ADMIN_API_KEY}"
```

```
export ADC_BACKEND=api7ee

export ADC_SERVER="https://{DASHBOARD_ADDR}"

export ADC_TOKEN="{DASHBOARD_TOKEN}"

export ADC_GATEWAY_GROUP="{GATEWAY_GROUP}"
```

Create the service and route:

adc.yaml

```
services:

  - name: csrf-doc-service

    labels:

      docs-example: csrf

    routes:

      - name: csrf-doc-route

        uris:

          - /anything/csrf-doc

        plugins:

          csrf:

            key: docs-csrf-secret-8f3d7c2a1b9e

    upstream:

      type: roundrobin

      nodes:

        - host: httpbin.org

          port: 80

          weight: 1
```

Preview the changes and confirm that they only affect resources for this example:

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=csrf
```

Review `diff.yaml`, then synchronize the labeled service:

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=csrf
```

[Set up the Ingress Controller and gateway](https://docs.api7.ai/ingress-controller/set-up-ingress-controller-and-gateway.md) in the `aic` namespace before continuing.

* Gateway API
* APISIX CRD

csrf-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - port: 80

      targetPort: 80

---

apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: csrf-doc-route

spec:

  plugins:

    - name: csrf

      config:

        key: docs-csrf-secret-8f3d7c2a1b9e

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: csrf-doc-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /anything/csrf-doc

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: csrf-doc-route

      backendRefs:

        - name: httpbin-external-domain

          port: 80
```

csrf-ic.yaml

```
apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: httpbin-external-domain

spec:

  type: ExternalName

  externalName: httpbin.org

  ports:

    - port: 80

      targetPort: 80

---

apiVersion: apisix.apache.org/v2

kind: ApisixPluginConfig

metadata:

  namespace: aic

  name: csrf-doc-route

spec:

  ingressClassName: apisix

  plugins:

    - name: csrf

      enable: true

      config:

        key: docs-csrf-secret-8f3d7c2a1b9e

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: csrf-doc-route

spec:

  ingressClassName: apisix

  http:

    - name: csrf-doc-route

      match:

        paths:

          - /anything/csrf-doc

      backends:

        - serviceName: httpbin-external-domain

          servicePort: 80

      plugin_config_name: csrf-doc-route
```

Apply the configuration:

```
kubectl apply -f csrf-ic.yaml
```

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[​](#submit-a-matching-token "Direct link to 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
```
