Optimize API client headers by method - only set Content-Type and CSRF header as needed
- Only set Content-Type header for requests with a body (POST, PUT, DELETE with body) - Only set X-BanGUI-Request CSRF header for mutating methods (POST, PUT, DELETE, PATCH) - GET, HEAD, OPTIONS requests no longer include unnecessary headers, reducing CORS preflights - Update Web-Development.md to clarify conditional header behavior - Add comprehensive tests for header behavior by HTTP method This reduces unnecessary CORS preflight requests on GET endpoints while maintaining CSRF protection on state-mutating requests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -119,8 +119,10 @@ fetchBans(24, ctrl.signal) // Pass the signal to enable cancellation on unmount
|
||||
All state-mutating requests (POST, PUT, DELETE, PATCH) automatically include the custom header `X-BanGUI-Request: 1` via the central API client. This protects against Cross-Site Request Forgery (CSRF) attacks by requiring a custom header that cross-site JavaScript cannot set without CORS preflight.
|
||||
|
||||
**How it works:**
|
||||
- The `request()` function in `api/client.ts` includes `"X-BanGUI-Request": "1"` in the default headers.
|
||||
- GET, HEAD, and OPTIONS requests are unaffected.
|
||||
- The `request()` function in `api/client.ts` conditionally sets headers based on the request method and body:
|
||||
- `Content-Type: application/json` is only set for requests with a body (POST, PUT, DELETE with body) to avoid unnecessary CORS preflights on GET requests.
|
||||
- `X-BanGUI-Request: 1` is only set for state-mutating requests (POST, PUT, DELETE, PATCH).
|
||||
- GET, HEAD, and OPTIONS requests are unaffected (no CSRF header, no Content-Type header).
|
||||
- Bearer token authentication bypasses the check (tokens are not CSRF-vulnerable).
|
||||
- The backend `CsrfMiddleware` validates this header for cookie-authenticated state-mutating requests.
|
||||
- Requests missing the header receive a `403 Forbidden` response.
|
||||
|
||||
Reference in New Issue
Block a user