csrf
Protects state-changing requests against cross-site request forgery.
csrfPriority 2980What it does
csrf refuses a write that does not carry the token the gateway handed out. On the route, every answer sets the token as a cookie named under Name. A POST without the token in the header of that same name is answered 401 with no csrf token in headers.
The token does not reach the header on its own. The page's script reads the cookie and copies its value into the header on each write, x-csrf-token in the example.
When to use it
- A web app that signs users in with a session cookie and posts forms to the orders API.
- An administration page where a link planted on another site must not change or delete orders in the signed-in user's name.
- A browser app on another origin that sends cookies, beside cors with Allow credential on.
Not for calls from servers and mobile apps that carry no cookies — see key-auth (Authenticates consumers with an API key sent in a header or query parameter) or letting a page on another origin read the API's answers — see cors (Adds CORS headers so browsers can call the API from other origins).
Set it up
Refuse writes that do not carry the token the browser was given
Every answer sets the token as a cookie; a browser does not send it back on its own, so the page's script copies the cookie's value into the x-csrf-token header on each write.
Set Key to <secret>, set Name to x-csrf-token and set Expires to 3600 seconds.
{
"key": "<secret>",
"name": "x-csrf-token",
"expires": 3600
}
Things to know
- Name — With
x-csrf-tokenhere, a first request is answered200with aSet-Cookieof that name, and aPOSTwithout the header is answered401withno csrf token in headers. - Name — Every response carries a fresh token under this name. GET, HEAD and OPTIONS pass without one; other methods need it.
- Key — An empty Key is refused when you save, because anyone could sign a token with it.
- Expires — At zero or less the age of a token is never checked and the cookie is dated for the moment it was set, so a browser drops it before it can be sent back.
- AdviceGenerate Key as a long random value, keep it out of shared files, and change it at a quiet hour.
Settings
The fields as the console shows them, section by section.
keystringRequiredA long random secret the tokens are signed with. Changing it refuses every token already handed out. Each token also carries its own timestamp and a random value. Stored on the engine and shown only to roles that manage this object.
namestringdefault apisix-csrf-tokenOne name for both the header the client sends and the cookie it reads the token from.
expiresintegerdefault 7200