Open::API example: a CSRF-protected petstore

A complete server and client driven by one OpenAPI 3.1 document (petstore.json), showing CSRF protection end to end.

Files

Run it

In one terminal:

perl examples/server.pl 5000

In another:

perl examples/client.pl http://127.0.0.1:5000

Or open http://127.0.0.1:5000/docs in a browser: ui => 1 on the server serves the built-in docs UI (see perldoc Open::API::UI; it needs the sibling Template::Stencil built). Log in via try-it-out on POST /login with security: [], then create a pet - the page reads the rotated csrf cookie and sends X-CSRF-Token on every unsafe call automatically.

Expected output from the client:

GET  /pets (anon)  -> 401 (not logged in)
POST /login        -> 200 (user=alice)
GET  /pets         -> 200 (user=alice)
POST /pets  (rex ) -> 201 ok (token rotated for next call)
POST /pets  (milo) -> 201 ok (token rotated for next call)
POST /pets  (aria) -> 201 ok (token rotated for next call)
DELETE /pets/1     -> 204

without csrf => 1 : POST /login -> 403 (blocked at the Origin check, as expected)

What to notice

See perldoc Open::API (the CSRF, SECURITY, RESPONSE HEADERS and CORS sections) and perldoc Open::API::Client for the full picture.