'enableCsrfValidation' => true,
'csrfParam' => 'csrfToken',
'csrfCookie' => [
'httpOnly' => false,// Must be false so JS can read CSRF token
'secure' => YII_ENV_PROD ? true : false,// True if you use HTTPS in production
'sameSite' => YII_ENV_PROD ? Cookie::SAME_SITE_NONE : Cookie::SAME_SITE_LAX,
],
does this look good for csrf token being send from yii2 backend restful api to frontend react web browser site
Assistant
User
'httpOnly' => false
Setting httpOnly: false is necessary if your React app reads the CSRF token from the cookie via JavaScript (e.g., document.cookie) to include it in AJAX requests.
However, this exposes the CSRF token cookie to JavaScript, which can be a slightly increased attack surface, so make sure you trust your frontend and avoid XSS vulnerabilities.
Alternative approach is to deliver the CSRF token via a JSON payload response or HTTP header, avoiding cookie exposure — but if you prefer this route, httpOnly=false is fine.
What if I sent the token via json and then used js-cookie to then store the token into a cookie?
Assistant
User
However, this exposes the CSRF token cookie to JavaScript, which can be a slightly
increased attack surface, so make sure you trust your frontend and avoid XSS
vulnerabilities.
Alternative approach is to deliver the CSRF token via a JSON payload response or
HTTP header, avoiding cookie exposure — but if you prefer this route, httpOnly=false
is fine.
Ok so what if I sent the csrf token via cookie, so the cookie is correctly sent and set via the backend
but also sent a json with additional string token that could be attached to the csrf token cookie but is also store
in hte backend?
Assistant
User
but if I use httpOnly and js can access it, how do i use the csrf token for forms and such, isn't this the entire point
Assistant
User
So, what’s the "entire point"?
The point of CSRF tokens is to prevent cross-site requests that are made without knowledge of a secret token. The server verifies any state-changing requests include the token:
If the token is stored in a cookie only, and HttpOnly, the browser sends it automatically with requests (because cookies are automatically attached).
But for AJAX or SPA calls, the server often expects the token to be sent in a custom header (commonly X-CSRF-Token) or in a hidden form field.
Since HttpOnly cookies cannot be read by JS, the frontend can't include that token inside headers or form fields unless the token is also delivered in some other way.
Assistant
User
Assistant
User
does yii2 backend session cookies effect request csrf token cookie?
Assistant
User
planned to use within my web config to prevent xss:
and:
/**
* Host Header Attack
* @url https://www.yiiframework.com/doc/guide/2.0/en/security-best-practices#avoiding-host-header-attacks
*
* Note: you should always prefer web server configuration for 'host header attack' protection
* instead of the filter usage. yii\filters\HostControl should be used only if server configuration
* setup is unavailable.
/
'as hostControl' => [
'class' => 'yii\filters\HostControl',
'allowedHosts' => [
'example.com',
'.example.com',
],
'fallbackHostInfo' => 'https://example.com',
],
Assistant
User
Assistant
User
I thought by extending the controller with the apiBaseController, the apiBaseController sets whats within it into
any controller that uses it, so i wouldnt need to add OptionAction::cass actions() to each controller? or public $enableCsrfValidation = false;
if these are already set in the apiBaseController
Assistant
User
'Access-Control-Allow-Credentials' => true,
Does this allow cookies or not? what you wrote is confusing:
Credentials (cookies) not allowed Set 'Access-Control-Allow-Credentials' => true in backend CORS and withCredentials=true in frontend
Assistant
User
protected function getAllowedOrigins(): array
{
originsEnv=_ENV['CORS_ORIGINS'] ?? getenv('CORS_ORIGINS') ?: '';
// Split into array, trim whitespace, remove empties
$origins = array_filter(array_map('trim', explode(',', $originsEnv)));
if (empty($origins))
{
// default origin for dev, adjust accordingly
$origins = ['http://localhost:1234'];
}
\Yii::error("Allowed Origins: " . json_encode($origins), __METHOD__);
return $origins;
}
< HTTP/1.1 405 Method Not Allowed
< Host: localhost:5000
< Date: Fri, 23 May 2025 14:19:14 GMT
< Connection: close
< X-Powered-By: PHP/8.2.28
< Allow: GET
< Content-Type: application/json; charset=UTF-8
< X-Debug-Tag: 683083e281c6c
< X-Debug-Duration: 8
< X-Debug-Link: /debug/default/view?tag=683083e281c6c
<
Closing connection 0
{"name":"Method Not Allowed","message":"Method Not Allowed. This URL can only handle the following request methods: GET.","code":0,"status":405,"type":"yii\web\MethodNotAllowedHttpException"
Assistant
The core problem is in this response:
HTTP/1.1 405 Method Not Allowed
Allow: GET
...
{"name":"Method Not Allowed","message":"Method Not Allowed. This URL can only handle the following request methods: GET."}
User
adding
public function actions()
{
return array_merge(parent::actions(), [
'options' => [
'class' => \yii\rest\OptionsAction::class,
],
]);
}
which is what I have in the apiBaseController did not solve the issue
public function actions()
{
return [
'options' => [
//'class' => OptionsAction::class,
'class' => '\yii\rest\OptionsAction',
],
];
}//*/
Ive tried both with no postive results
Assistant
User
[
'class' => 'yii\rest\UrlRule',
'controller' => ['test'],
'prefix' => 'api',
// Note: To use versioning for the API: 'prefix' => 'api/v1',
'pluralize' => false,
'extraPatterns' => [
'index' => 'index',
],
],
ok i did this for the test controller
Assistant
User
ok so what is the curl -X command to test
Assistant
To test CORS preflight (OPTIONS request) for your API endpoint, use the following curl command:
Your last curl request shows a successful OPTIONS preflight response:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 3600
Access-Control-Allow-Headers: Content-Type, Authorization, X-CSRF-Token
...
This means:
✅ Your Yii2 backend now correctly:
Handles OPTIONS requests (no more 405 error)
Includes all proper CORS headers for your React frontend origin
User
this works only for the test controller, which bags the question what is wrong with my apiBaseController and cors
Assistant
User
Assistant
User
public function beforeAction(action)
{
// Call parent's beforeAction first and check if it allows proceeding
if (!parent::beforeAction(action))
{
return false;
}
// CSRF token validation for POST, PUT, PATCH requests
$request = \Yii::$app->request;
/**
* If your base or subclass controllers override beforeAction(), make sure:
* They allow OPTIONS requests without throwing errors or blocking them.
*/
if ($request->method === 'OPTIONS')
{
// Skip CSRF validation for CORS preflight requests
return true;
}
if (in_array($request->method, ['POST', 'PUT', 'PATCH', 'DELETE']))
{
$token = $request->headers->get('X-CSRF-Token');
if (!$token)
{
$params = $request->getBodyParams();
$token = $params[$request->csrfParam] ?? null;
}
if (!$request->validateCsrfToken($token))
{
\Yii::warning('Invalid CSRF token for request to ' . $request->url);
throw new badRequestHttpException('Invalid CSRF token.');
}
}
return true;
}
Assistant
User
your snippets and ramblings does not help, send full code examples or refactor my code to how you suggest I should fix my issue
so Access-Control-Expose-Headers' => ['X-CSRF-Token'], is really meant for native react apps? and not a frontend web browser site/app?
Assistant
User
if I did send the csrf token via the header along with the cookie, could I not in theory do what I wanted to in the first place? Which was during our earlier convo, have a secondary security check of the csrf token itself, making sure its correct and store it possibly within memory and do checks between the memory and cookie version before returning it within forms? would this not help with xss attacks?
Assistant
User
but as you said its only saved until refresh, so i be grabbing the csrf token often. and headers are readable, so how secure is my idea really? other then adding a more complex gathering, for something that really the prevention is quite simple, making sure trusted sources are set in the config.
Assistant
User
so sending the csrf token is not needed and stick to what works at this time. using cookies for csrf tokens validation passed via form and checked on the backend.
Assistant
Yes, exactly — that is the straightforward and proven approach used by most frameworks and applications:
What works well and is recommended:
Send the CSRF token via a cookie (typically with HttpOnly: false if frontend JS needs to read it, or embedded in rendered forms if server-rendered).
Include the token in AJAX requests, either as a request header or form field.
Is 'X-CSRF-Token' needed in Access-Control-Allow-Headers?
Yes, if your frontend sends the CSRF token via the X-CSRF-Token HTTP header in AJAX requests, then you must include 'X-CSRF-Token' in the backend's Access-Control-Allow-Headers response header for CORS to succeed.
Why?
When a browser makes a cross-origin AJAX request with custom headers (like X-CSRF-Token), it first does a CORS preflight OPTIONS request to check if the server allows that header.
The server replies with an Access-Control-Allow-Headers header listing which request headers the browser is allowed to send.
User
so this is strickly the frontend sending to the backend gotcha
Assistant
Exactly!
Access-Control-Allow-Headers is a response header from the backend that tells the browser which request headers are permitted when the frontend (browser) makes cross-origin requests.
So:
If your frontend JavaScript sends a custom header like X-CSRF-Token in an AJAX/fetch request to the backend,
Then your backend must include'X-CSRF-Token' in the Access-Control-Allow-Headers header in its CORS preflight (OPTIONS) response,
Otherwise, the browser will block the request due to CORS policy.
To summarize:
Scenario
Need 'X-CSRF-Token' in Access-Control-Allow-Headers
Access-Control-Allow-Headers is a server response header that tells the browser which request headers the frontend is allowed to send to the backend during cross-origin requests.
Access-Control-Expose-Headers is a server response header that tells the browser which response headers the frontend JavaScript is allowed to read from the backend’s response (when doing cross-origin requests).
"Let me know if you want examples on how to set these on the backend or how to handle them in your frontend code!"
ok, using axios
Assistant
User
Assistant
User
// src/services/apiClientServices.ts
import axios, { AxiosRequestConfig } from 'axios';
import { ENDPOINTS } from '../constants/apiConstants';
import { csrfTokenManager } from './csrfServices';
import logger from '../utils/loggerUtils';
Assistant
User
Assistant
Your setup is clean, follows best practices, and the design is sound! Here's a concise summary and confirmation addressing your points:
User
. Passing csrf as a parameter to submitSignupStageZeroEmail
In your current code, the csrf parameter is accepted but not used explicitly, since Axios interceptor attaches it automatically.
You can remove the csrf argument from this function unless you want to inject CSRF token in the body explicitly.
Alternatively, if you want to keep it, consider using it consistently, e.g.:
(2025-05-23T17:22:27.942Z) [csrfServices.ts] Could not fetch CSRF token from backend Error: CSRF token in cookie does not match token from backend response.
backend:
public function actionCsrfToken(): array
{
$request = \Yii::$app->request;
if (!$request->isGet)
{
throw new BadRequestHttpException('Only GET requests are allowed.');
}
$token = $request->getCsrfToken();
// Explicitly add CSRF cookie to response (forces Set-Cookie header)
\Yii::$app->response->cookies->add(
new Cookie([
'name' => $request->csrfParam,
'value' => $token,
'httpOnly' => false,// Always false for csrf token
'secure' => YII_ENV_PROD ? true : false,// true if you use HTTPS in production
'sameSite' => YII_ENV_PROD ? Cookie::SAME_SITE_NONE : Cookie::SAME_SITE_LAX,
])
);
// No need to set format here explicitly if contentNegotiator behavior is active,
//\Yii::$app->response->format = Response::FORMAT_JSON;
\Yii::$app->response->statusCode = 200;
return [
'csrfParam' => $request->csrfParam,
'csrfToken' => $token,
];
}
Assistant
User
Assistant
User
if i already have web config for reponse csrf token cookie do i i need todo this:
\Yii::app−>responserequest->csrfParam,
'value' => $token,
'httpOnly' => false,
'secure' => YII_ENV_PROD,
'sameSite' => YII_ENV_PROD ? Cookie::SAME_SITE_NONE : Cookie::SAME_SITE_LAX,
'path' => '/', // ensure cookie always overrides previous cookies on all paths
]));
Assistant
User
loggerUtils.ts:151 (2025-05-23T17:37:00.399Z) [csrfServices.ts] Token from backend response: dE5pllpg5EM9PyVaP7I_67sVXq17fDa9DvwI9lPlPyM7IFzXA1amM1decC0GyE6IzSc27jM7VetJsVLGANZ9VA==
loggerUtils.ts:235 (2025-05-23T17:37:00.399Z) [csrfServices.ts] Could not fetch CSRF token from backend ReferenceError: Cannot access 'cookieToken' before initialization
at fetchCsrfToken (csrfServices.ts:58:54)
at async csrfServices.ts:106:38
Assistant
The error
ReferenceError: Cannot access 'cookieToken' before initialization
at fetchCsrfToken (csrfServices.ts:58:54)
means that inside your function fetchCsrfToken() you are trying to use the variable cookieTokenbefore declaring or initializing it.
This is a JavaScript/TypeScript runtime error related to variable scoping, generally caused by something like:
if (cookieToken !== csrfToken) { // using cookieToken here before declaration
...
}
const cookieToken = getCsrfTokenFromCookie(); // declared **after** usage - wrong!
How to fix:
Make sure that the variable cookieToken is declared and initialized before you use it anywhere in your function.
User
Assistant
The error you reported earlier:
ReferenceError: Cannot access 'cookieToken' before initialization
is caused because you use cookieTokenbefore declaring it here:
User
cleared the browser and same issue:
(2025-05-23T17:42:43.525Z) [csrfServices.ts] Token from backend response: FuOAwLzINPvrLl8qFaKGXvVXMfYyxK2bd2cY7PHaJntvlbj164NSjtpfK31N2_IuwmdArFSy7qJBX1CUs58XIw==
loggerUtils.ts:235 (2025-05-23T17:42:43.525Z) [csrfServices.ts] Could not fetch CSRF token from backend Error: CSRF token in cookie does not match token from backend response.
at fetchCsrfToken (csrfServices.ts:69:9)
at async csrfServices.ts:108:38
if (!csrfParam || !csrfToken) {
throw new Error('Failed to fetch CSRF token');
}
// Optionally read cookie but do not throw if mismatch
const cookieToken = getCsrfTokenFromCookie();
logger.log('csrfServices.ts', 'Token from backend response:', csrfToken);
logger.log('csrfServices.ts', 'Token from cookie:', cookieToken);
(2025-05-23T17:52:19.125Z) [csrfServices.ts] Token from backend response: 54mJccSIrSINw09BDbJN2v1gCT_7uEITht21_wzbmeO48cg-lv7lGzS7BSV84RKqyiwwb5z6MkKxgsLMe6Hxrw==
loggerUtils.ts:235 (2025-05-23T17:52:19.125Z) [csrfServices.ts] Could not fetch CSRF token from backend Error: CSRF token in cookie (7914ed609a40a3df10e5b24985f6e22a4fa5e8496763dfb36a988d448c464447a:2:{i:0;s:9:"csrfToken";i:1;s:32:"_xAORvH99xJdqS_p7L9PgBpQ7_w3wzhL";}) does not match token from backend response (54mJccSIrSINw09BDbJN2v1gCT_7uEITht21_wzbmeO48cg-lv7lGzS7BSV84RKqyiwwb5z6MkKxgsLMe6Hxrw==).
at fetchCsrfToken (csrfServices.ts:70:9)
at async csrfServices.ts:109:38
Assistant
User
Assistant
User
export const CSRF_COOKIE_NAME = 'csrfToken';
export function getCsrfTokenFromCookie(): string | undefined
{
logger.log('All cookies via js-cookie:', Cookies.get());
return Cookies.get(CSRF_COOKIE_NAME);
}
this is what I have already:
you wrote:
Make sure your front end only reads the real CSRF cookie, NOT the session cookie
If you see both cookies, your code should get only the CSRF cookie:
export function getCsrfTokenFromCookie(): string | undefined {
return Cookies.get(CSRF_COOKIE_NAME); // fetch real CSRF cookie here
}
Assistant
User
Assistant
User
Assistant
User
(2025-05-23T18:31:24.039Z) [All cookies via js-cookie:] {_csrf: 'b88683a1cdbf5117af248edc0b6fd338889ea31fdbe2d3e015…rf";i:1;s:32:"N3xdWwCf6ZvHPXyDYqD9TowhckQ5d8z7";}'}_csrf: "b88683a1cdbf5117af248edc0b6fd338889ea31fdbe2d3e01566445252eb0586a:2:{i:0;s:5:"_csrf";i:1;s:32:"N3xdWwCf6ZvHPXyDYqD9TowhckQ5d8z7";}"[[Prototype]]: Object
loggerUtils.ts:235 (2025-05-23T18:31:24.039Z) [csrfServices.ts] Could not fetch CSRF token from backend Error: CSRF token cookie missing.
at fetchCsrfToken (csrfServices.ts:63:9)
at async csrfServices.ts:111:38
overrideMethod @ hook.js:608
loggerUtils.ts:151 (2025-05-23T18:31:24.041Z) [All cookies via js-cookie:] {_csrf: 'b88683a1cdbf5117af248edc0b6fd338889ea31fdbe2d3e015…rf";i:1;s:32:"N3xdWwCf6ZvHPXyDYqD9TowhckQ5d8z7";}'}_csrf: "b88683a1cdbf5117af248edc0b6fd338889ea31fdbe2d3e01566445252eb0586a:2:{i:0;s:5:"_csrf";i:1;s:32:"N3xdWwCf6ZvHPXyDYqD9TowhckQ5d8z7";}"[[Prototype]]: Objectconstructor: ƒ Object()hasOwnProperty: ƒ hasOwnProperty()isPrototypeOf: ƒ isPrototypeOf()propertyIsEnumerable: ƒ propertyIsEnumerable()toLocaleString: ƒ toLocaleString()toString: ƒ toString()valueOf: ƒ valueOf(): ƒ (): ƒ (): ƒ (): ƒ (): (...)get : ƒ ()set : ƒ ()
Assistant
User
Assistant
User
// src/services/apiClientServices.ts
const apiClient = axios.create({
baseURL: API_BASE_URL,
withCredentials: true,// sends cookies automatically with cross-origin requests
headers:
{
'Content-Type': 'application/json',
},
timeout: 10000,// Aborts the request and throws an error after 10 seconds
});
/**
Add request interceptor
Axios interceptors allow you to intercept and modify requests or responses globally before
they are handled by your individual API calls.
Request interceptors run before a request is sent, letting you add headers (e.g., auth tokens),
modify request config, or log requests.
Response interceptors run after receiving a response, enabling centralized error handling, token
refresh logic, or response transformation.
Using interceptors helps keep your API client DRY, consistent, and easier to maintain.
/
apiClient.interceptors.request.use(
async (config: AxiosRequestConfig) =>
{
/*
* Read token from the non-HttpOnly cookie or from csrf-token endpoint
* add X-CSRF-Token header to mutating requests (POST, PUT, PATCH, DELETE)
*/
const method = config.method ? config.method.toLowerCase() : '';
if (['post', 'put', 'patch', 'delete'].includes(method))
{
const token = csrfTokenManager.getToken();
Assistant
Your apiClientServices.ts setup with Axios interceptors looks solid and is the recommended approach for inserting the CSRF token into mutating requests. Here's a bit of a cleanup and explanation to ensure the interceptor works perfectly:
import axios, { AxiosRequestConfig } from 'axios';
import { csrfTokenManager } from './csrfServices';
const apiClient = axios.create({
baseURL: API_BASE_URL, // Your backend base URL
withCredentials: true, // Send cookies on cross-origin requests
headers: {
'Content-Type': 'application/json', // JSON body by default
},
timeout: 10000, // Timeout after 10 seconds
});
// Request interceptor to add CSRF token header to mutating HTTP methods
apiClient.interceptors.request.use(
async (config: AxiosRequestConfig) => {
const method = config.method ? config.method.toLowerCase() : '';
if (['post', 'put', 'patch', 'delete'].includes(method)) {
const token = csrfTokenManager.getToken();
if (token) {
config.headers['X-CSRF-Token'] = token;
}
}
return config;
},
error => Promise.reject(error)
);
export default apiClient;
User
so what do you suggest?
Assistant
User
but it dose not work!!! as ive shown you...
Assistant
The SameSite attribute on a web cookie controls whether the cookie is sent along with cross-site requests, helping to mitigate certain types of cross-site request forgery (CSRF) attacks.
There are three main values for SameSite:
SameSite=Lax
Cookies are sent with same-site requests and with top-level navigations (e.g., when the user clicks a link to your site from another site).
Cookies are not sent with most cross-site subrequests (like loading images or iframes from another site).
This is a balanced, secure default that allows typical user navigation but prevents many CSRF attacks.
Example: If your site is example.com, and the user clicks a link on othersite.com pointing to example.com, the cookie with SameSite=Lax will be sent.
SameSite=None
Cookies are sent in all contexts, including cross-site requests, but must also be marked as Secure (sent only over HTTPS).
This allows cookies to be sent with requests initiated from other sites, such as iframes, AJAX calls, or resources loaded cross-site.
Used when you explicitly want your cookie to be available in cross-site contexts (e.g., for third-party services, or when embedding your site in other sites).
If you set SameSite=None but not Secure, the cookie will be rejected by modern browsers.
SameSite=Strict (for completeness)
Cookies are sent only with same-site requests — even top-level navigations initiated by the user will not send these cookies if the site is coming from a different origin.
This is the most restrictive setting and provides the strongest CSRF protection.
Summary
SameSite value
When cookie is sent
Use Case
Lax (default)
Sent with same-site requests & top-level cross-site navigations (e.g., link clicks)
Most common; balances security and usability
None
Sent with all requests (cross-site and same-site), requires Secure
Let me know if you want details on how browsers enforce these rules or how to choose the right value!
Let's analyze your Yii2 configuration snippet in the context of a RESTful API backend (Yii2) and a frontend React app deployed on a different origin (domain).
Your backend (Yii2) issues a CSRF token in a cookie named 'csrfToken'.
The React frontend needs to read the token from the cookie (hence 'httpOnly' => false) to send it in headers or requests.
You want CSRF protection to work properly both locally (dev) and in production.
Does this config look good?
1. 'httpOnly' => false
Setting httpOnly: falseis necessary if your React app reads the CSRF token from the cookie via JavaScript (e.g., document.cookie) to include it in AJAX requests.
However, this exposes the CSRF token cookie to JavaScript, which can be a slightly increased attack surface, so make sure you trust your frontend and avoid XSS vulnerabilities.
Alternative approach is to deliver the CSRF token via a JSON payload response or HTTP header, avoiding cookie exposure — but if you prefer this route, httpOnly=false is fine.
2. 'secure' => YII_ENV_PROD ? true : false
This ensures the cookie is sent over HTTPS only in production, which is a good practice.
During local development with HTTP, secure is false so the cookie will still be set.
Just make sure your production environment actually uses HTTPS, or the cookie won't be set/sent.
In production, this sets SameSite=None, which allows cross-site requests to send the cookie.
Assuming your React frontend is hosted on a different origin (domain, port, or scheme), this is correct and necessary.
Important: When using SameSite=None, the cookie must also be 'secure' => true.
In dev, SameSite=Lax is acceptable because likely frontend and backend share origin or you are simulating less strict cross-origin behavior.
Additional considerations:
Cross-Origin cookies require SameSite=None + Secure=true. You have this covered in production.
Your frontend React app must send credentials (cookies) with fetch or axios, e.g., { credentials: 'include' }
CSRF token sent as a cookie is read by the React app and included in header or body for requests.
Your backend must validate CSRF token properly (enableCsrfValidation => true).
The cookie domain and path might matter if frontend and backend domains differ or you want to scope the cookie; check if you need to specify those.
Summary:
Your config is correct and appropriate for:
Using CSRF tokens stored in cookies readable by JS,
Sending CSRF cookies cross-site (React <> Yii2 on different domains),
Using HTTPS + secure cookies in production,
Using lax cookies locally for development convenience.
Just make sure:
Your React app sends requests with credentials (cookies).
HTTPS is enabled in production.
You trust frontend JS to read the CSRF cookie safely.
Yii2 backend validates CSRF token in the incoming requests against the token sent by client.
If you want, I can also suggest code examples for the React side on how to send the CSRF token in requests!
Great question! Let me clarify the implications and options around that approach.
Scenario you described:
Backend sends the CSRF token in the JSON response body (e.g., after login or a dedicated CSRF endpoint).
Frontend reads this token (e.g., via fetch or axios).
Frontend uses a library like js-cookie to set the token into a cookie.
Subsequent requests include the CSRF token as required (from cookie or directly in headers).
What about setting the token cookie via JS instead of the backend?
Pros:
You don’t need to set httpOnly: false on the server cookie, because the token cookie is not set by the server.
You can keep the server’s CSRF cookie httpOnly: true or simply not set it at all.
Potentially reduces attack surface because you control exactly when and how the token cookie is created by JS.
Cons / Considerations:
The cookie set via JS will always be accessible to JavaScript (httpOnly can’t be set by JS).
You can't set Secure or SameSite=None attributes on cookies purely via document.cookie or js-cookie — modern browsers don't allow Secure or SameSite attributes to be reliably set by client-side code. (Actually, most cookie attributes can be set with js-cookie, including Secure and SameSite; see below.)
If your frontend’s origin domain differs from your backend’s domain, you might struggle to set the cookie correctly without backend support (e.g., cookie domain and path might not match, and cross-origin cookie writes have restrictions).
You must ensure the cookie is set with the correct options (Secure, SameSite=None) for cross-site cookie requests.
The cookie set by JS will be visible to JS, so XSS remains a risk. But you already accept that if you rely on JS reading the token.
Can js-cookie set Secure and SameSite flags?
Yes, js-cookie supports setting cookie options such as Secure and SameSite. For example:
This is crucial if you want cross-site cookies with proper attributes.
Practical implications:
If your backend and frontend are on different domains (e.g., api.example.com and app.example.com or totally different domains), setting and sending cross-site cookies is tricky.
Cross-site cookies require the cookie to be set with SameSite=None and Secure=true.
If your React app sets the cookie on the browser via js-cookie from the frontend JavaScript, the cookie domain is the React app’s domain.
If your backend expects the cookie to come from its own domain, it won’t receive the CSRF cookie set on another domain.
To make cookies accessible cross-domain, you’d have to coordinate domains, use a shared parent domain plus subdomains, or rethink how you pass the CSRF token.
Alternative (common) pattern:
Backend does NOT use cookies for CSRF tokens.
Backend provides the CSRF token in JSON (X-CSRF-Token) response on login or an initial API call.
Frontend stores the token in memory or in localStorage or even js-cookie but under its own domain.
Frontend sends the CSRF token explicitly as a header (X-CSRF-Token) on all mutating requests.
No cookie-based CSRF token required or used.
Backend validates X-CSRF-Token header MUST match the backend-side token stored (e.g., in session or a DB).
This avoids the whole domain/cookie dilemma.
Recommendation:
If your RESTful API is stateless or you don’t want to deal with cross-site cookie complexity, send CSRF tokens via JSON and send them back via custom headers.
Store tokens in JS memory or a safe place on the client side.
Avoid setting cookies manually unless you have full control over domain and can handle Secure / SameSite properly.
Summary:
Approach
Backend sets cookie with httpOnly=false
Frontend sets cookie from JS (via js-cookie)
CSRF token in JSON + header (no cookie)
Cookie Secure and SameSite
Backend can set directly, including Secure, SameSite flags
Can be set by js-cookie but cookie domain is frontend domain
N/A
Cookie domain control
Backend controls domain
Cookie domain = frontend domain
N/A
XSS exposure
Token cookie accessible if httpOnly=false
Token cookie accessible
Token accessible in JS
Cross-origin support
Works if SameSite=None + Secure + Proper domain
Works for frontend domain only; cross-origin issues may arise
Works well, token passed explicitly with requests
Complexity
Medium
Medium to complex (domain issues)
Simple and recommended for SPAs + REST APIs
So if you control both frontend and backend domains, and have HTTPS in production:
Backend setting cookie with httpOnly=false, plus SameSite=None and Secure=true is often easiest and more reliable for cross-site CSRF tokens.
Otherwise, delivering token via JSON and managing it entirely in frontend JS state and headers is a clean and often better modern approach.
If you want, I can help with a sample implementation of either approach!
You're describing a hybrid approach where:
The backend sets the CSRF token cookie normally (with appropriate flags), so it is automatically sent with requests by the browser.
In addition, the backend sends a JSON response containing an extra token string (or some related data).
This extra value is stored server-side (e.g., in the session or database), and can be used in CSRF validation logic combined with the cookie.
What are you trying to achieve with this?
Possibly improving CSRF protection?
Adding a second factor or tying the CSRF token to a per-request or per-session secret?
Or maybe trying to avoid httpOnly: false while still enabling front-end token verification?
How could this work?
Set cookie with CSRF token:
The cookie is set by the backend and marked (e.g.)
'httpOnly' => true, // cookie not accessible to JS (most secure!)
'secure' => true,
'sameSite' => 'None'
This way the cookie is sent automatically by the browser, but JavaScript cannot read it directly.
Send additional token in JSON response:
The backend sends, e.g., { "csrfExtraToken": "some-random-string" } in the API response body.
Backend stores the extra token server-side:
For example, inside the user session or some persistent store.
Client sends back both tokens on state-changing requests:
The cookie is sent automatically by the browser.
The client reads the additional token from JavaScript memory (from JSON) and includes it in the request header (or body).
Backend verifies:
The CSRF token from the cookie (retrieved by the backend from the request cookies).
The additional token sent explicitly (header or body) matches what’s stored server-side (and/or corresponds correctly to the cookie).
Benefits of this approach:
Cookie is HttpOnly: More secure, not readable by JS, so XSS cannot steal the CSRF token directly.
Extra token sent in JSON is readable by JS and sent explicitly, so your frontend can send it back securely.
Double check: Backend verifies that both tokens correspond or belong together, adding a layer of security.
Could help with defense-in-depth or layering CSRF token checks.
Considerations / Possible limitations:
You must maintain logic on backend to associate the extra token with the cookie token/session.
This is not a standard pattern out-of-the-box in Yii2 or most frameworks, so you’ll need custom validation.
Complexity increases: you now manage two related tokens, plus on client side you handle this extra token in addition to relying on cookie.
Frontend must store and send the extra token correctly.
Example use case where this makes sense:
If you want a CSRF token cookie to be HttpOnly (so no JS token stealing risk)
But your frontend has to send a token explicitly in headers for your API
So you add an additional token to be sent via JSON that the frontend can safely keep and send
Your backend only accepts requests if both cookie and header token are present and valid together.
Alternative simpler approach:
Send CSRF token in JSON response (not cookie)
Store in JS memory/localStorage/js-cookiewith no httpOnly cookie at all
Frontend includes token in header for all mutating requests
Server validates token from header
Pros: Simpler and avoids cookie hassle Cons: Token in JS context, so susceptible to XSS if present
Summary
Approach
Cookie HttpOnly?
Token readable by JS?
Complexity
Use-case
CSRF token cookie only, httpOnly = false
No
Yes
Low
Common, simple, but token exposed to JS
CSRF token cookie only, httpOnly = true
Yes
No
Low
Secure but frontend can't read the token to set HTTP headers
Token only via JSON, set/storage managed in frontend JS
N/A
Yes
Low
Simple SPA-friendly, but token exposed in JS
If you want maximal security combined with frontend flexibility, your suggested approach is valid but requires you to implement:
Backend: logic to generate/store both tokens, and validate both on incoming requests.
Frontend: correctly read/store/attach the extra token on requests.
If you want, I can help sketch sample Yii2 backend validation and React frontend usage for this approach!
Great question! This touches on the core tradeoff of CSRF token management and the purpose of the HttpOnly flag on cookies.
Key points:
HttpOnly cookies cannot be accessed via JavaScript (e.g., document.cookie). This means your frontend JS cannot read the cookie value.
If your frontend needs to read the CSRF token (e.g., to insert it as a hidden field in HTML forms, or to add it as a header in AJAX requests), then the CSRF token must be accessible in JavaScript.
Making the CSRF cookie HttpOnly prevents JS from reading the token, which is great for security but problematic if your frontend SPA or JS needs that token to submit forms or AJAX requests safely.
So, what’s the "entire point"?
The point of CSRF tokens is to prevent cross-site requests that are made without knowledge of a secret token. The server verifies any state-changing requests include the token:
If the token is stored in a cookie only, and HttpOnly, the browser sends it automatically with requests (because cookies are automatically attached).
But for AJAX or SPA calls, the server often expects the token to be sent in a custom header (commonly X-CSRF-Token) or in a hidden form field.
Since HttpOnly cookies cannot be read by JS, the frontend can't include that token inside headers or form fields unless the token is also delivered in some other way.
How do traditional web apps vs SPAs handle this?
Traditional server-rendered forms
Server renders forms with the CSRF token inside hidden input fields.
The CSRF token does not need to be read from cookies by JS.
Cookies can be HttpOnly or not, but for these, the token is embedded in the page.
When submitted, the token is sent back in the request body, and server validates.
SPA / JS frontend apps
The backend usually needs to expose the CSRF token to JS.
So server either:
Sets a non-HttpOnly cookie with the CSRF token, which JS can read (as you have now),
Or sends the CSRF token as part of an initial JSON response or dedicated endpoint.
The frontend JS then reads this token and includes it in headers (e.g., X-CSRF-Token) or request body.
In this case, cookie must be accessible to JS (HttpOnly: false).
This exposes the token to JS, hence potential risk via XSS.
Summary:
Scenario
HttpOnly cookie?
How frontend gets token
Remarks
Classic server-rendered forms
Usually yes
Token embedded directly in HTML form fields
Secure and no JS access needed
SPA or API-based frontend
Usually no (false)
Token in non-HttpOnly cookie or JSON response, read by JS
Needed so JS can include token in headers
Double-submit cookie technique
No (false)
Token cookie readable by JS & sent as header
Requires JS access to cookie
What if you want secure token but JS needs to read it?
There’s an inherent tradeoff:
If HttpOnly=true → JS cannot read token → difficult for SPA to correctly include token in headers
If HttpOnly=false → token readable by JS → more exposed to XSS attacks
Ways to mitigate risk if you must expose token to JS:
Strongly protect your app against XSS (using Content Security Policy, input sanitization, etc.)
Scope cookie appropriately (path, domain)
Use short-lived tokens or rotate tokens frequently
Consider SameSite=Lax or Strict cookies to reduce CSRF risks from other sites
Use other security layers (CORS, authentication tokens, etc.)
Alternative approaches:
Use double-submit cookie pattern:
Cookie is accessible to JS (non-HttpOnly)
JS reads that token and sends it as header
Server validates token sent in header matches cookie
Or send CSRF token only via JSON — no cookie at all, store and manage tokens fully in frontend JS.
TL;DR:
You need HttpOnly: false on your CSRF cookie for SPA/frontend JavaScript to read and include the CSRF token in headers or forms, otherwise you lose the ability to access it for AJAX or JS-driven requests.
This is the "entire point" in SPA/API scenarios. The downside is slightly increased exposure to JS-based attacks, which must be mitigated separately.
If you want, I can help you with best practices/code examples for your particular Yii2 + React setup!
Exactly — you've summarized the fundamental challenge with CSRF tokens and HttpOnly cookies in SPA/API contexts very well. Let me expand a bit to clarify and consolidate the explanation.
The “Entire Point” of CSRF Tokens — Recap and Explanation
Goal:
Prevent unauthorized cross-site requests originating from other domains/users that do not know a secret token. When your user is logged in, malicious sites could trick their browser into making requests your backend would accept if there were no CSRF protections.
How tokens help:
The backend requires any state-changing request (POST, PUT, DELETE) to include a secret secret token only your frontend should know.
Where tokens live:
There are two main ways:
Cookie-only token (and validated via double-submit cookie):
Token stored only in a cookie. The browser automatically sends the cookie with requests. Vulnerable unless cookie has strong SameSite and/or token is also sent as header.
Token sent explicitly (header or form field), and validated against a secure value server-side:
This requires the frontend to read the token and include it explicitly in the request headers or body.
Why HttpOnly interferes in SPA/AJAX setup
HttpOnly cookie = Inaccessible to JS:
JavaScript cannot read the token value from such cookies, so your React app can’t extract the token to add it as a header (X-CSRF-Token).
SPAs / AJAX calls usually don’t submit forms with hidden fields:
They rely on APIs called via fetch or axios and must include CSRF tokens explicitly in request headers.
Hence, the CSRF token needs to be exposed to client-side JavaScript — which means the cookie (if used as token storage) cannot be HttpOnly, or the token must come from another source (e.g., JSON response body).
Typical solutions given this:
Approach
HttpOnly cookie?
JS can read token?
Usage
Server-rendered forms
Usually yes
No
Token embedded in forms
SPA or AJAX APIs with token in cookie
No
Yes
Token read from cookie and sent in headers
SPA or AJAX with token from JSON response
N/A
Yes
Token sent from API response, saved in JS
Token-only in JS/localStorage
No
Yes
No cookie needed
So in your scenario:
If you want your React frontend to send the CSRF token in headers for AJAX requests, your backend must provide tokens accessible to JS.
That means httpOnly: false on the CSRF token cookie, or delivering the token separately in JSON or headers.
You accept the slight exposure of token to JS (and thus potential XSS risk).
Meanwhile, you mitigate by securing your frontend from XSS attacks and using modern cookie attributes (Secure, SameSite).
Important note:
Browsers send cookies automatically in requests as per normal cookie policy.
However, for CSRF protection, servers usually check the token sent explicitly in a request header or body parameter, not just an incoming cookie.
So your React app reads the CSRF token from cookie or JSON, then adds it as, e.g., X-CSRF-Token header.
This enables you to verify that the request originated from your frontend code (which had access to the token), blocking forged requests from other sites.
Final summary
Because SPA apps rely on explicit inclusion of CSRF tokens in AJAX request headers, those tokens must be accessible in JavaScript. Therefore, cookies storing those tokens cannot be HttpOnly. This is the "entire point" behind the widely used approach in modern frontends.
If you want, I can help with concrete Yii2 backend + React frontend snippet examples showing this in action. Would you like that?
Traditional server-rendered forms
Server renders forms with the CSRF token inside hidden input fields.
The CSRF token does not need to be read from cookies by JS.
Cookies can be HttpOnly or not, but for these, the token is embedded in the page.
When submitted, the token is sent back in the request body, and server validates.
SPA / JS frontend apps
The backend usually needs to expose the CSRF token to JS.
So server either:
Sets a non-HttpOnly cookie with the CSRF token, which JS can read (as you have now),
Or sends the CSRF token as part of an initial JSON response or dedicated endpoint.
The frontend JS then reads this token and includes it in headers (e.g., X-CSRF-Token) or request body.
In this case, cookie must be accessible to JS (HttpOnly: false).
This exposes the token to JS, hence potential risk via XSS.
OK, trying to wrap my mind around this. Since frontend is a React web browser and does in fact us axios for calls. The goal is to follow the best security practices to keep users safe, I dont know them all and why I come and speak with you a security export. This is the backend code we have so far:
Web config for csrf token:
'request' => [
'class' => 'yii\web\Request',
'enableCsrfValidation' => true,
'csrfParam' => 'csrfToken',
'csrfCookie' => [
'httpOnly' => false,// Must be false so JS can read CSRF token
'secure' => YII_ENV_PROD ? true : false,// True if you use HTTPS in production
'sameSite' => YII_ENV_PROD ? Cookie::SAME_SITE_NONE : Cookie::SAME_SITE_LAX,
],
'cookieValidationKey' => '***',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
class ApiBaseController extends Controller
{
// disable built-in automatic validation
public $enableCsrfValidation = false;
public function behaviors(): array
{
$behaviors = parent::behaviors();
$behaviors['corsFilter'] =
[
'class' => Cors::class,
'cors' => [
// Allowed request origins - set via env variable or fallback default
'Origin' => $this->getAllowedOrigins(),
/**
* Allowed HTTP methods in CORS preflight
* Can be overridden in child controllers to narrow methods per controller
*
* If left empty or not set here, 'Cors' defaults to all common HTTP verbs allowed.
*
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],//*/
/**
* Allowed HTTP headers clients can use during the actual requests.
* This should include Authorization for bearer tokens and other headers you expect.
*
* Common headers your React app will send are:
* - Authorization (for Bearer token)
* -- Your backend CORS must allow both 'Authorization' and 'Content-Type' in Access-Control-Allow-Headers.
* -- Also, 'OPTIONS' requests must bypass authentication for CORS
* preflight (see 'except' => ['options'] in authenticator behavior).
* - Content-Type (usually application/json)
* - X-Requested-With (sometimes added by libraries)
* - X-CSRF-Token (if using CSRF protection, mostly for stateful apps)
* - Accept (To ask API which format it supports) Often handled automatically, usually no CORS action needed
*
* Note: For native apps or SPAs that send JWT tokens via the Authorization: Bearer <token> header in AJAX/fetch requests,
* this header must be allowed by CORS to avoid preflight errors by the browser.
*/
'Access-Control-Allow-Headers' => ['Content-Type', 'Authorization', 'X-Requested-With', 'X-CSRF-Token'],
'Access-Control-Expose-Headers' => ['X-CSRF-Token'],
// Allow credentials (cookies, HTTP auth, etc.) in requests
'Access-Control-Allow-Credentials' => true,
// Preflight OPTIONS request cache duration (seconds)
'Access-Control-Max-Age' => 3600,
],
];
$behaviors['contentNegotiator'] =
[
'class' => ContentNegotiator::class,
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
];
$behaviors['authenticator'] =
[
'class' => CompositeAuth::class,
/**
* Except
* - Skips auth on all OPTIONS requests
* - Allows unauthenticated access to these actions
*/
'except' => ['options'],
'authMethods' => [
CookieJwtAuth::class,// Cookie based for browsers - Check 'access_token' cookie
/**
* For cross-platform frameworks (React Native) or native apps, you’ll need to:
* Store the tokens in secure storage modules (e.g., react-native-keychain or SecureStore).
* Manually attach the access token in the Authorization header with every API request:
*
* headers: {
* Authorization: `Bearer ${token}`,
* // other headers
* }
*
* On token expiry, call your refresh endpoint and update stored tokens accordingly.
*/
HttpBearerAuth::class,// Header based for native app/api clients//*/
],
];
return $behaviors;
}
/**
* Csrf-token - Before Action
*/
public function beforeAction($action)
{
// Call parent's beforeAction first and check if it allows proceeding
if (!parent::beforeAction($action))
{
return false;
}
// CSRF token validation for POST, PUT, PATCH requests
$request = \Yii::$app->request;
// Skip CSRF validation for CORS preflight requests
if ($request->method === 'OPTIONS')
{
return true;
}
if (in_array($request->method, ['POST', 'PUT', 'PATCH', 'DELETE']))
{
$token = $request->headers->get('X-CSRF-Token');
if (!$token)
{
$params = $request->getBodyParams();
$token = $params[$request->csrfParam] ?? null;
}
if (!$request->validateCsrfToken($token))
{
\Yii::warning('Invalid CSRF token for request to ' . $request->url);
throw new badRequestHttpException('Invalid CSRF token.');
}
}
return true;
}
public function actions()
{
return [
'options' => [
'class' => OptionsAction::class,
],
];
}
protected function getAllowedOrigins(): array
{
$originsEnv = $_ENV['CORS_ORIGINS'] ?? getenv('CORS_ORIGINS') ?: '';
// Split into array, trim whitespace, remove empties
$origins = array_filter(array_map('trim', explode(',', $originsEnv)));
if (empty($origins))
{
// default origin for dev, adjust accordingly
$origins = ['http://localhost:1234'];
}
return $origins;
}
}
final class ApiSecurityController extends ApiBaseController
{
// Not sure if this should be disabled or enabled:
//public $enableCsrfValidation = false;
/**
* Enable Csrf Validation
* This will disable CSRF validation within the entire Controller, by
* setting $enableCsrfValidation Controller property to false:
*
public $enableCsrfValidation = false;//*/
public function behaviors(): array
{
$behaviors = parent::behaviors();
/**
* CORS Filter
* - Override allowed HTTP methods for CORS preflight specifically for UserController
*/
$behaviors['corsFilter']['cors']['Access-Control-Request-Method'] = ['GET', 'POST', 'OPTIONS'];
/**
* Authenticator Filter
* - Extend 'except' so signup and reset-password actions do not require auth
* - Ensure uniqueness after merge in case of duplicates
*/
if (!isset($behaviors['authenticator']['except']))
{
$behaviors['authenticator']['except'] = [];
}
$behaviors['authenticator']['except'] = array_merge(
$behaviors['authenticator']['except'], [
'csrf-token',
'refresh-jwt-token',
'options',// Add 'options' HTTP verb to skip auth for CORS preflight
]
);
// Remove duplicates just in case
$behaviors['authenticator']['except'] = array_unique(
$behaviors['authenticator']['except']
);
/**
* Verb Filter
* @url https://www.yiiframework.com/doc/guide/2.0/en/structure-filters#verb-filter
*
* Note: Adding OPTIONS to VerbFilter can cause issues because the VerbFilter is meant
* to filter actual HTTP verb usage against defined actions. Usually, no controller
* action is defined for OPTIONS.
*/
$behaviors['verbFilter'] =
[
'class' => VerbFilter::class,
'actions' =>
[
'csrf-token' => ['GET'],
/**
* If supporting native apps with GET
*/
'refresh-jwt-token' => ['POST', 'GET'],// Change to ['POST', 'GET']//*/
//'refresh-jwt-token' => ['POST']
],
];
return $behaviors;
}
// Not sure if this is needed
public function beforeAction($action): bool
{
if (in_array($action->id, ['csrf-token, submit-form']))
{
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
// This is my Get for csrf token if not set
public function actionCsrfToken(): array
{
$request = \Yii::$app->request;
if (!$request->isGet)
{
throw new BadRequestHttpException('Only GET requests are allowed.');
}
$token = $request->getCsrfToken();
// Explicitly add CSRF cookie to response (forces Set-Cookie header)
\Yii::$app->response->cookies->add(
new Cookie([
// Not sure if this is needed since web config also sets the cookie config
'name' => $request->csrfParam,
'value' => $token,
'httpOnly' => false,// Always false for csrf token
'secure' => YII_ENV_PROD ? true : false,// true if you use HTTPS in production
'sameSite' => YII_ENV_PROD ? Cookie::SAME_SITE_NONE : Cookie::SAME_SITE_LAX,
])
);
// No need to set format here explicitly if contentNegotiator behavior is active,
//\Yii::$app->response->format = Response::FORMAT_JSON;
\Yii::$app->response->statusCode = 200;
/*return [
'csrfParam' => $request->csrfParam,
'csrfToken' => $token,
];*/
}
}
Thanks for sharing your detailed setup! You’ve clearly put a lot of thought and effort into it. I’ll provide a thorough explanation of how your current Yii2 backend CSRF setup works in conjunction with a React SPA frontend that uses Axios, and how to optimize for best security practices.
Your Current Setup Recap
CSRF Cookie is set with:
httpOnly = false — so React/JS can read it
secure = true in production (HTTPS only)
sameSite = 'None' in production — allows cross-site cookies (important for frontend/backend on different domains)
CSRF token sent to frontend via:
automatic cookie set by Yii2
plus you have an API endpoint actionCsrfToken that explicitly sends the token in JSON + resets the cookie
Frontend (React/Axios) need to:
read token from the non-HttpOnly cookie or from csrf-token endpoint
add X-CSRF-Token header to mutating requests (POST, PUT, PATCH, DELETE)
API Controllers:
Disable automatic CSRF validation with controller-level property enableCsrfValidation = false
Implement manual CSRF token validation in beforeAction() checking header or body param 'X-CSRF-Token'
This makes it easier for React to fetch and read the token initially, before reading from cookie.
4. Manual CSRF token validation in beforeAction() is fine here because automatic validation is disabled for your API controllers
You check X-CSRF-Token header first, falling back to request param.
This aligns with your frontend sending token explicitly in the header.
Nice that you skip CSRF validation on OPTIONS requests (CORS preflight).
5. Ensure Axios is configured properly on frontend to send cookies and headers
Must set { withCredentials: true } in Axios config to send cookies cross-site.
Add the CSRF token header from cookie or from your actionCsrfToken API, e.g.:
import Cookies from 'js-cookie';
const csrfToken = Cookies.get('csrfToken'); // cookie name = 'csrfToken'
axios.defaults.withCredentials = true;
axios.defaults.headers.common['X-CSRF-Token'] = csrfToken;
// Alternatively, fetch token from API and set header dynamically
6. CORS Setup looks good for this use case
Allowing credentials and exposing X-CSRF-Token header
Allowing origins from environment / default localhost for dev.
Allowed headers include Authorization, Content-Type, and X-CSRF-Token.
7. Small notes for your controller code:
public function beforeAction($action): bool
{
if (in_array($action->id, ['csrf-token', 'submit-form'])) // fixed: you need the list as array of strings
{
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
Make sure the array is properly formed (['csrf-token', 'submit-form']) and quotes are used correctly else you may skip CSRF validation incorrectly.
Summary & Recommendations for Your Setup
Item
Recommended / Status
csrfCookie 'httpOnly' => false
✅ Necessary, enable JS access to CSRF token cookie
✅ Good idea, just return the token JSON for frontend to consume
Frontend JS reads cookie or API token
✅ Ok, make sure react axios sends withCredentials: true and sets X-CSRF-Token header
Manual CSRF validation in beforeAction()
✅ Fine, good to skip OPTIONS requests
CORS setup
✅ Looks correct for credentials and headers
Protect against XSS
❗ Very important since CSRF token is JS-accessible
To further improve security:
Use Content Security Policy (CSP) headers to dramatically reduce XSS risk.
Regularly review your frontend JS to avoid introducing XSS vulnerabilities.
Consider rotating CSRF tokens periodically (on login, or after N requests).
Scope your CSRF cookie domain and path as narrowly as possible.
Monitor security headers like Strict-Transport-Security.
If feasible, serve frontend and backend from the same origin to allow stricter cookie policies.
If you want, I can also help you with:
Sample React/Axios code for fetching and applying the CSRF token.
Sample Yii2 configuration snippets or suggestions for other security headers.
Guidance on Content Security Policy setup.
Would you like me to prepare some example React client code that works with your current backend CSRF setup?
Good question!
Short answer:
No, the Yii2 backend session cookie and the CSRF token cookie are separate cookies and serve different purposes. One does not directly affect the other, but both are often required together for a full authenticated and CSRF-protected session.
Explanation:
Yii2 Session Cookie:
Typically named PHPSESSID (default) or whatever you configure as your session cookie name.
It holds the server-side session ID.
Sent automatically by the browser with each request to identify the user session on the backend.
Usually HttpOnly and Secure (if HTTPS).
Responsible for maintaining user login state or any data stored in server session.
CSRF Token Cookie:
In your Yii2 config, e.g., named csrfToken.
Holds the CSRF token string for the client to send back on mutating requests.
May or may not be HttpOnly depending on your config (false if frontend JS needs to read the token).
Designed to protect against cross-site request forgery attacks.
The token is validated by Yii2 on state-changing requests matching the token in the request header or body.
How they relate in practice:
The session cookie is required to maintain the backend session.
The CSRF cookie is required to share the CSRF token with the frontend (usually JS or forms).
Yii2's CSRF validation depends on the token submitted in requests matching the token stored in the session, not exclusively the cookie.
The cookie exists so the client can have access to the CSRF token for inclusion in requests, but Yii2’s server-side validation checks the token against the server-side session storage for that user's session.
Your specific question:
Does the session cookie affect the request CSRF token cookie?
They are separate cookies, so they don’t affect each other at the HTTP cookie level.
However, CSRF token validation depends on the session, since the token stored server-side is saved in the session. If the session cookie is not present or invalid, the CSRF token validation will fail because the server doesn't have the token to validate against.
In other words:
If the browser doesn't send the session cookie (or it is invalid), the backend will not be able to load the correct session.
Without the session, the backend cannot look up the CSRF token to validate against the submitted token.
So session cookie indirectly affects CSRF validation, not by changing the CSRF cookie, but by determining whether the server can validate that token.
In summary:
Cookie Type
Purpose
Interaction with other cookie
Session cookie
Maintain user session
Needed to load session and CSRF token server-side
CSRF token cookie
Share CSRF token with client
Independent cookie, but token validated against session data
Final note
If you have a stateless API (no PHP session), then CSRF tokens generally don’t work this way. You’d typically use other protection schemes (e.g., JWT with CORS, custom headers, etc.).
If you are using Yii2 session, keep both cookies working and consistent.
Feel free to ask if you want a detailed example of how Yii2 stores the CSRF token in session and how cookies come into play!
Your approach to add security headers and protect against Host header attacks is solid — good job thinking about these layers! Here’s a detailed review and suggestions for your Yii2 config snippets:
1. Content-Security-Policy (CSP) header via response component
CSP policy "default-src 'self'; script-src 'self';" is a good minimal starting point that restricts resources and scripts to originate from your own domain only.
Consider expanding CSP for your app needs — e.g., if you load fonts, styles, images from CDNs or have inline styles or scripts, you may need to whitelist those.
If you use inline scripts or eval, script-src 'self' would block them — which is often a good thing for security.
CSP reporting: You may want to add report-uri or report-to directives to monitor potential CSP violations without breaking functionality during development.
Test CSP in "report-only" mode before enforcing — this can be done by setting header Content-Security-Policy-Report-Only so you can identify blocked resources without breaking your app.
You can automate and manage security headers with Yii2 behaviors or middleware (depending on your app structure).
Example: Enhanced security headers setup in Yii2 config
Your basic CSP header as shown is an excellent start.
Use HostControl filter if you cannot secure Host headers at server/proxy level.
Consider adding complementary security headers.
Tailor CSP to your app’s external resource needs.
Test CSP in report-only mode prior to enforcement.
Always pair these headers with XSS prevention best practices in app code.
If you want, I can help prepare a more detailed CSP header tailored to your app or help with implementing CSP report-only mode and reporting!
// src/services/csrfServices.ts
import Cookies from 'js-cookie';
import apiClient from './apiClientServices';
import { ENDPOINTS } from '../constants/apiConstants';
import logger from '../utils/loggerUtils';
/**
CSRF Token manager class.
Handles fetching token from backend, reading from cookie,
caching token internally, and providing easy access.
On app startup, call:
await csrfTokenManager.init();
In your axios interceptor (or wherever you send API requests):
import { csrfTokenManager } from './csrfServices';
export type CsrfData =
{
csrfParam: string;
csrfToken: string;
};
/**
Fetch the CSRF token and param from the backend endpoint.
This triggers the backend to set the CSRF cookie.
Throws an error if token or param are missing.
*/
export async function fetchCsrfToken(): Promise
{
const response = await apiClient.get(ENDPOINTS.security.csrfToken);
const { csrfParam, csrfToken } = response.data;
if (!csrfParam || !csrfToken)
{
throw new Error('Failed to fetch CSRF token');
}
const cookieToken = getCsrfToken();
if (!cookieToken || cookieToken !== csrfToken)
{
throw new Error('CSRF token in cookie does not match token from backend response.');
}
return { csrfParam, csrfToken };
}
/**
Read the CSRF token directly from the CSRF cookie.
Returns undefined if cookie is missing.
*/
export function getCsrfTokenFromCookie(): string | undefined
{
return Cookies.get(CSRF_COOKIE_NAME);
}
class CsrfTokenManager
{
private csrfParam?: string;
private csrfToken?: string;
/**
* Initialize the token manager by fetching token from backend,
* and then synchronizing with the token in cookie.
* Call once on app startup.
*/
async init()
{
try
{
const { csrfParam, csrfToken } = await fetchCsrfToken();
this.csrfParam = csrfParam;
this.csrfToken = csrfToken;
}
catch (error)
{
logger.warn('csrfServices.ts', 'Could not fetch CSRF token from backend', error);
}
// Override with cookie token if available (more reliable/up-to-date)
const cookieToken = getCsrfTokenFromCookie();
if (cookieToken)
{
this.csrfToken = cookieToken;
}
}
/**
* Get the current CSRF token to be used for headers.
* Prefers cookie token if it exists, else falls back to cached token.
*/
getToken(): string | undefined
{
// Prefer cookie token if available (more up to date)
const cookieToken = getCsrfTokenFromCookie();
if (cookieToken)
{
this.csrfToken = cookieToken;
return cookieToken;
}
// Fall back to fetched token
return this.csrfToken;
}
/**
* Get the CSRF param name (cookie name / form param name).
*/
getParam(): string | undefined
{
return this.csrfParam;
}
}
// Export a singleton CSRF token manager instance to be used app-wide.
export const csrfTokenManager = new CsrfTokenManager();
this is my frontend code and how it handles csrf token, I keep having issues with:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/api-security/csrf-token. (Reason: CORS request did not succeed). Status code: (null).
The errors you’re seeing:
CORS header 'Access-Control-Allow-Origin' missing
Cross-Origin Request Blocked: Same Origin Policy disallows ...
Status code 405 on OPTIONS preflight request
indicate that your backend is not properly handling CORS preflight OPTIONS requests for your /api/api-security/csrf-token endpoint.
Why is this happening?
When your React frontend (likely running on localhost:3000 or similar) calls http://localhost:5000/api/api-security/csrf-token, it’s a cross-origin request (because ports differ).
Browsers send a CORS preflight OPTIONS request before the GET request to check if the server will accept the actual request.
If the backend does not respond correctly to that OPTIONS request (missing CORS headers, 405 Method Not Allowed), the browser will block the real request.
How to fix this in your Yii2 backend?
You need to:
Ensure OPTIONS requests to /api/api-security/csrf-token are allowed and respond with proper CORS headers.
Make sure your CORS filter includes this endpoint and handles all preflight requests.
Allow credentials on CORS because you use cookies and CSRF tokens.
Confirm the CORS filter is applied for all relevant controllers and actions.
Step-by-step fix:
1. Confirm Yii2 CORS filter configuration
Your ApiBaseController has a CORS filter behavior:
Make sure this behavior is attached to your controller serving /api/api-security/csrf-token.
Your ApiSecurityController should extend ApiBaseController (it appears so).
Make sure corsFilter is not overridden or disabled in ApiSecurityController.
2. Add OPTIONS action in your controller if missing
Yii2 by default requires an action to handle OPTIONS requests if your app wants to respond properly to preflight.
In your base API controller you have:
public function actions()
{
return [
'options' => [
'class' => \yii\rest\OptionsAction::class,
],
];
}
This correctly provides OPTIONS handler.
Verify this is inherited and available in ApiSecurityController.
If it is missing, add:
public function actions()
{
return [
'options' => [
'class' => \yii\rest\OptionsAction::class,
],
];
}
in ApiSecurityController.
3. Make sure your CORS config allows your frontend origin http://localhost:3000 or wherever React runs
Your getAllowedOrigins() should return array like:
['http://localhost:3000', 'http://localhost:1234'] // adjust according to your dev environment
Double-check your environment variable or fallback.
If your React app uses, say, http://localhost:3000, but getAllowedOrigins() returns only default http://localhost:1234 or empty, the backend will deny CORS.
Remember in CORS spec, if you send credentials, the server cannot use a wildcard '*' for Access-Control-Allow-Origin, it must specify the exact origin.
5. Verify your frontend call URL and protocol match exactly
CORS origin matching is strict, must match scheme, domain, port.
If your frontend runs on http but your backend is https or vice versa, or ports differ, CORS will fail.
Also, ensure the request URL does not have trailing slashes or mismatches.
Additional debug tips:
Use browser DevTools Network tab to inspect OPTIONS requests:
Look at Request and Response headers.
Make sure the response to OPTIONS includes correct Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, and Access-Control-Allow-Credentials.
If backend returns 405 Method Not Allowed for OPTIONS, it means no handler for OPTIONS request. Confirm OptionsAction is enabled.
Temporarily test with CORS disabled (like browser extensions) to isolate if CORS is root cause.
Summary:
Issue
Fix recommendation
Missing or 405 on OPTIONS requests
Add OptionsAction to controller actions
CORS headers missing or incorrect
Ensure yii\filters\Cors configured and applied
Allowed origins do not include frontend origin
Update getAllowedOrigins() with your React origin
Credentials (cookies) not allowed
Set 'Access-Control-Allow-Credentials' => true in backend CORS and withCredentials=true in frontend
Origin mismatch
Match frontend URL origin exactly
Example minimal fix snippet (in ApiSecurityController.php):
public function behaviors(): array
{
$behaviors = parent::behaviors();
// Make sure corsFilter is enabled or merged properly
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::class,
'cors' => [
'Origin' => $this->getAllowedOrigins(),
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
'Access-Control-Allow-Headers' => ['Content-Type', 'Authorization', 'X-Requested-With', 'X-CSRF-Token'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 3600,
],
];
return $behaviors;
}
public function actions()
{
return [
// Respond to OPTIONS requests for preflight
'options' => [
'class' => \yii\rest\OptionsAction::class,
],
];
}
If after that you still have issues, please share your full controller hierarchy and your frontend exact URL and axios config, and I can help you debug further.
You're correct in principle: when your controller extends ApiBaseController, it inherits all its public/protected properties and methods, including the behaviors and actions defined there.
1. About actions() and OPTIONS handling
If ApiBaseController defines an actions() method that returns the OPTIONS action handler, it will be automatically inherited by any subclass controller (like your ApiSecurityController), unless you override actions() in the subclass.
Example:
class ApiBaseController extends Controller
{
public function actions()
{
return [
'options' => [
'class' => OptionsAction::class,
],
];
}
}
If you now define:
class ApiSecurityController extends ApiBaseController
{
// No 'actions()' method here
}
Then ApiSecurityController::actions()is inherited, and your OPTIONS requests will be handled.
Caveat: overriding actions() in subclass
If you define your own actions() method in ApiSecurityController, e.g.:
class ApiSecurityController extends ApiBaseController
{
public function actions()
{
return [
// your own actions here, but you do NOT include 'options'
];
}
}
then you override and replace the inherited actions array, and you lose the 'options' action unless you explicitly include it.
To fix that:
When overriding actions(), merge parent actions:
public function actions()
{
return array_merge(parent::actions(), [
// add or override your actions here
]);
}
2. About $enableCsrfValidation = false
Same principle applies:
If declared as a public property in ApiBaseController, it will be inherited by subclasses.
Unless you redeclare or override it in the subclass, the inherited value remains.
Example:
class ApiBaseController extends Controller
{
public $enableCsrfValidation = false;
}
class ApiSecurityController extends ApiBaseController
{
// unless overridden here, enableCsrfValidation remains false
}
This means you do not need to redeclare $enableCsrfValidation = false in every subclass unless you want a different behavior.
Summary
Scenario
Behavior
Recommendation
Subclass does NOT define actions()
Inherits parent actions() including OPTIONS handler
No changes needed—OPTIONS handled automatically
Subclass overridesactions()
Overrides and replaces parent's actions — OPTIONS handler lost unless merged or redefined
Use array_merge(parent::actions(), [...])
$enableCsrfValidation inherited
Subclass inherits parent's property value
Declare only in ApiBaseController
What to check in your case:
Does ApiSecurityController define its own actions()?
If yes, make sure it merges or adds back OPTIONS action from parent.
Is $enableCsrfValidation declared anywhere in subclass (to override)?
If yes, it overrides the base setting.
Is your ApiSecurityController certainly extending ApiBaseController?
Example correct usage if you need to customize actions in subclass but preserve OPTIONS:
class ApiSecurityController extends ApiBaseController
{
public function actions()
{
return array_merge(parent::actions(), [
// your other actions here (if any)
]);
}
}
If still unsure, you can always test what actions your controller exposes by calling:
In sum: yes, inheritance works as you expect — but watch out for accidental overrides of actions() removing inherited behavior.
Great question! I'll clarify this because CORS + cookies (credentials) can be confusing.
What is Access-Control-Allow-Credentials?
It is a response header sent by the server.
When set to true, it allows the browser to expose the response to frontend JavaScript when credentials are included in the request.
Credentials mean:
Cookies
HTTP authentication information
Client-side SSL certificates
Does it "allow cookies"?
Yes, it permits the browser to send cookies and authentication info with cross-origin requests and expose responses back to JavaScript.
But:
To send cookies with cross-origin fetch or XMLHttpRequest, the browser-side request must specify { credentials: 'include' } (e.g., axios.defaults.withCredentials = true).
The server must respond with:
Access-Control-Allow-Credentials: true
And most importantly, the Access-Control-Allow-Origin header cannot be '*' (wildcard) in this case. It must be an exact origin, e.g., http://localhost:3000.
What happens if Access-Control-Allow-Credentials is missing or false?
Browser won't send cookies or authorization headers on cross-origin requests.
Browser won't allow frontend JS to access the response if credentials are involved.
What if frontend sets withCredentials: true but backend does not set Access-Control-Allow-Credentials: true?
Browser will block the response due to CORS policy. Request is sent, but response is ignored by frontend JS (appears as failed).
Conversely, what if backend sends Access-Control-Allow-Credentials: true but frontend request is not with credentials?
No cookies are sent, but the response headers allow credentials if they were sent.
Summary: How to enable cookies cross-origin with CORS
Step
What to do
Server
Set 'Access-Control-Allow-Credentials' => true header
Server
Set 'Access-Control-Allow-Origin' => 'http://your-frontend-origin' (no wildcard '*')
Client (JS/Axios/Fetch)
Set withCredentials: true in your requests
Why must Access-Control-Allow-Origin NOT be '*' when using credentials?
Security reasons in the spec prevent browsers from allowing credentialed requests with wildcard origin, to avoid exposing user credentials to untrusted sites.
axios.defaults.withCredentials = true; // enables sending cookies with cross-domain calls
TL;DR
Access-Control-Allow-Credentials: true tells the browser "it's OK to send cookies/auth info along with this cross-origin request and allow JS access to response" — but only if your frontend code also opts in with withCredentials: true.
If you want, I can explain more about how it works with CSRF tokens and cookie security!
the entries are JSON-encoded strings with escaped slashes (\/). In PHP strings, forward slashes do not need escaping, and browsers expect plain origin strings like "http://localhost:3000".
What matters here is what is actually stored in the $origins array and what your CORS filter sends in the Access-Control-Allow-Origin response header.
Potential problem:
If you passed these strings directly (with backslashes) as allowed origins, some implementations might see it as different from "http://localhost:3000" (no backslash).
That would cause your backend to reject or ignore valid frontend origins in the CORS check, causing "Missing Allow Origin" errors.
How to verify:
Add a debug var_dump or logging of the $origins array before returning:
This means your allowed origins are correctly set (no escaped slashes in actual strings), so the origins themselves are not causing the CORS failure.
So what else could cause your CORS errors? Here's a checklist focused on your Yii2 setup:
1. Make sure your Axios requests use the exact allowed origin
React app runs on, say, http://localhost:3000
Backend allows http://localhost:3000
If your React app is served from a slightly different URL (http://localhost:3000/ vs without trailing slash or different port), it should not cause a problem, but double-check exact URL in DevTools → Network → Request Headers → Origin.
2. Confirm CORS filter is applied and returning headers on OPTIONS preflight
Your backend must return appropriate CORS headers on every OPTIONS request.
Ensure OptionsAction is declared on controllers serving your endpoints:
public function actions()
{
return [
'options' => [
'class' => \yii\rest\OptionsAction::class,
],
];
}
This is crucial for successful preflight.
3. Ensure preflight (OPTIONS) requests are allowed and not blocked or returning 405
If your backend returns 405 Method Not Allowed or no CORS headers on OPTIONS, browser blocks the actual request.
If all above is set properly and you still get errors, can you share:
Exact request & response headers from the browser’s DevTools (especially OPTIONS preflight)
Backend logs/errors on OPTIONS request?
Feel free to ask if you'd like help verifying those headers and configs!
Your Yii2 backend is not handling the OPTIONS preflight request on /api/api-security/csrf-token.
WHY?
When your React frontend sends a cross-origin request, the browser sends an OPTIONS preflight request to check if the request is allowed.
Your backend is telling the browser only GET is allowed on this endpoint.
The server does NOT respond correctly to OPTIONS.
The browser then blocks the actual request, causing your CORS error.
HOW TO FIX IT?
Add an OPTIONS handler (OptionsAction) to this controller (or ensure it is inherited from ApiBaseController!)
Steps:
Make sure your ApiSecurityController has the actions() method returning OptionsAction:
public function actions()
{
return array_merge(parent::actions(), [
'options' => [
'class' => \yii\rest\OptionsAction::class,
],
]);
}
This registers the OPTIONS HTTP method handler, which simply returns allowed HTTP methods and appropriate CORS headers.
If you don't override actions() in ApiSecurityController, it will inherit from parent controller (good). But since you're getting 405, probably you have overridden it without including options.
Verify your CORS filter is applied properly:
Make sure the controller behaviors include your CORS filter as you shared earlier.
Additional tips:
Try sending OPTIONS request after you fix this, you should see Allow header listing allowed methods including OPTIONS, e.g.:
Allow: GET, OPTIONS
Response must include CORS headers (Access-Control-Allow-Origin, Access-Control-Allow-Methods, etc.)
Why is this crucial?
The browser will block any real request that requires preflight if OPTIONS fails.
Correct OPTIONS handling is mandatory in Yii2 REST API controllers for CORS to work.
Summary
Your /api/api-security/csrf-token currently only handles GET.
Add the OPTIONS action handler in controller actions() to fix 405.
Confirm CORS headers on OPTIONS requests.
This will resolve the "CORS Missing Allow Origin" and related CORS errors.
If you want, I can help you refactor your controller to correctly support OPTIONS and CORS!
If adding the OptionsAction in your controller's actions() didn't fix the problem, here are several things to check and try to troubleshoot why your Yii2 backend still returns 405 Method Not Allowed for the OPTIONS request on /api/api-security/csrf-token:
1. Confirm your controller inheritance and where actions() is defined
You say your ApiSecurityController extends ApiBaseController.
ApiBaseController already defines actions() method that returns 'options' => OptionsAction::class.
If ApiSecurityController also defines actions() that returns only the 'options' action but does NOT call parent::actions(), then all other actions, including your GET action that serves the CSRF token, are lost.
This causes routing issues because the request dispatcher cannot find your real action and might fallback to 405.
What to do:
Check you do NOT override actions() in child controller unless you merge with parent actions.
Here’s what you want in ApiSecurityController only if you must override actions():
public function actions()
{
// merge parent's actions with your own
return array_merge(parent::actions(), [
// any controller-specific custom actions here
]);
}
OR simply do NOT define actions() in ApiSecurityController at all, so it uses the parent actions() from ApiBaseController.
2. Check your routing rules and URL rules
Verify your URL manager is correctly routing /api/api-security/csrf-token to appropriate controller/action.
Sometimes, URL rules can interfere with OPTIONS requests.
Ensure HTTP verb restrictions are set properly and OPTIONS requests are not blocked or restricted by routing rules.
3. Make sure your behaviors() include Cors filter properly and is NOT overridden wrongly
Cors behavior must be on the controller handling the endpoint to respond properly to OPTIONS.
If overridden or missing in ApiSecurityController, add or merge with parent's behaviors.
Example (in ApiSecurityController):
public function behaviors()
{
return array_merge(parent::behaviors(), [
// add or override behaviors if needed
]);
}
Or simply remove behaviors() from child controller if not needed.
4. Debug with a simple test action
Try adding a trivial action in your controller to test OPTIONS:
public function actionTest()
{
return ['message' => 'Hello'];
}
Then test OPTIONS request to /api/api-security/test endpoint. See if the 405 persists.
5. Use Yii2 debug toolbar or logging to trace request handling
Check whether your OPTIONS request reaches the controller or is blocked earlier.
Enable debug logging for route parsing.
6. If your API is used with web server (Nginx, Apache), verify that:
Server does NOT block or handle OPTIONS differently.
No rewrite rules interfere with OPTIONS requests.
7. Minimal complete example:
If issues persist, try creating a minimal controller just to test CORS OPTIONS handling:
class TestController extends \yii\rest\Controller
{
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::class,
'cors' => [
'Origin' => ['http://localhost:3000'],
'Access-Control-Request-Method' => ['GET', 'OPTIONS'],
'Access-Control-Allow-Headers' => ['Content-Type', 'X-CSRF-Token'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 3600,
],
];
return $behaviors;
}
public function actions()
{
return [
'options' => [
'class' => \yii\rest\OptionsAction::class,
],
];
}
public function actionIndex()
{
return ['status' => 'ok'];
}
}
Test OPTIONS request to /test/index.
If this works, compare it with your real controller.
Summary checklist for your ApiSecurityController:
Does NOT override actions(), or if it does, merges parent actions()
Does NOT override behaviors() to remove parent's CORS filter
ApiBaseController defines actions() including OPTIONS handler
Routing and URL rules allow OPTIONS method
Web server passes OPTIONS requests to PHP
If none of these help, please share:
Your full ApiSecurityController code, especially any overrides of actions() and behaviors()
Your URL Manager rules
Response headers of OPTIONS request (if any)
Your web server config (Nginx or Apache) related to /api
Happy to assist further!
Thanks for sharing! Based on your UrlRule configuration:
GET api/test/index → TestController::actionIndex()
Plus automatically supports OPTIONS on those routes (but only if OPTIONS handler is defined in actions())
To ensure OPTIONS preflight works on this controller:
Your TestController must extend yii\rest\Controller or your ApiBaseController (which should extend yii\rest\Controller or yii\web\Controller with appropriate REST handlers).
Your TestController must define the actions() method with OPTIONS handler:
public function actions()
{
return [
'options' => ['class' => \yii\rest\OptionsAction::class],
];
}
Your TestController should define actionIndex() method:
public function actionIndex()
{
return ['status' => 'ok'];
}
The CORS filter must be attached as a behavior to TestController:
If CORS headers are set properly, you should see Access-Control-Allow-Origin in the response.
Let me know if you want help interpreting the output!
The 500 Internal Server Error means your Yii2 backend threw an exception or encountered an error while handling the OPTIONS request. Since this is a server-side error, the main focus is debugging your Yii2 backend.
Next steps to troubleshoot and fix this:
1. Use Yii debug toolbar or logs to identify error details
Check your Yii2 application error log files (usually in runtime/logs/app.log or runtime/logs/error.log) for stack trace and details about what caused the error.
Also use the debug toolbar's link shown in the header: X-Debug-Link: /debug/default/view?tag=68308bef3cbca
— If debug is enabled in your dev environment, this URL shows full error and stack trace.
2. Common reasons for 500 on OPTIONS requests in Yii2 REST controllers:
Your controller's actions() method is not properly set (missing OPTIONS handler or conflicts).
Your CORS filter behavior is misconfigured or throwing internal exceptions.
A custom behavior or event handler attached to beforeAction or similar causes an error when the HTTP method is OPTIONS.
3. Verify your REST controller setup for OPTIONS:
Example minimal TestController for CORS + OPTIONS:
namespace app\controllers\api;
use yii\rest\Controller;
use yii\filters\Cors;
class TestController extends Controller
{
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = [
'class' => Cors::class,
'cors' => [
'Origin' => ['http://localhost:3000'],
'Access-Control-Request-Method' => ['GET', 'POST', 'OPTIONS'],
'Access-Control-Allow-Headers' => ['Content-Type', 'Authorization', 'X-CSRF-Token'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 3600,
],
];
return $behaviors;
}
public function actions()
{
return [
'options' => ['class' => \yii\rest\OptionsAction::class]
];
}
public function actionIndex()
{
return ['status' => 'success'];
}
}
4. Test that your controller does not block OPTIONS in beforeAction
If you override beforeAction(), ensure you allow OPTIONS requests to pass without errors.
Example:
public function beforeAction($action)
{
if (\Yii::$app->request->method === 'OPTIONS') {
return true; // Allow OPTIONS requests, bypass CSRF or auth checks if needed
}
return parent::beforeAction($action);
}
5. Temporarily disable CSRF validation and authentication to isolate problem
In behaviors() temporarily disable or loosen auth and CSRF validation.
This helps isolate whether the error comes from your custom logic.
6. Check webserver (Nginx/Apache) error logs
The problem may also be at the PHP or webserver level; check those logs for additional clues.
Summary:
500 error means server-side exception — check logs and debug toolbar.
Make sure controller correctly defines actions() with OPTIONS handler.
Make sure CORS behavior is configured properly.
Check beforeAction() logic especially for OPTIONS method.
Temporarily disable complex logic like CSRF/auth to isolate issue.
If you want, share the relevant controller code (TestController or your failing API controller), beforeAction(), and CORS behavior config to help diagnose further!
Closing connection 0
Allows credentials (cookies)
Allows intended methods and headers
What to do next?
Try your React app again — browser should no longer block the request due to CORS preflight.
Next test the actual GET, POST or other requests your app sends, ensuring:
Axios/fetch is configured with withCredentials: true
CSRF token is read and sent in headers
Backend CSRF token validation passes
Recap: What fixed your issue?
Most likely you correctly added/support your controllers with:
yii\rest\OptionsAction in the actions() method
CORS filter (yii\filters\Cors) behavior configured properly
Allowed origins include your React app origin (http://localhost:3000)
Final suggestions for robust CORS and CSRF handling:
Keep Access-Control-Allow-Credentials: true to allow cookies.
Make sure your frontend always sends withCredentials: true in requests.
Serve frontend and backend over HTTPS in production.
Use an explicit list of allowed origins, never '*', when allowing credentials.
Rotate CSRF tokens securely and validate properly in backend.
Log and monitor errors for CORS or CSRF issues.
If you want, I can help you review or improve your frontend Axios setup for CSRF tokens too!
Congrats on resolving the OPTIONS preflight CORS problem! 🎉
Since the CORS preflight OPTIONS requests work correctly on your TestController, but not for other controllers extending your ApiBaseController (like ApiSecurityController), the issue very likely lies in how CORS and the OPTIONS handler are configured or inherited in ApiBaseController and its subclasses.
Common pitfalls & things to check in ApiBaseController and subclasses:
1. actions() method in ApiBaseController and subclasses:
ApiBaseController must declare actions() including the OPTIONS handler:
public function actions()
{
return [
'options' => ['class' => \yii\rest\OptionsAction::class],
];
}
If a subclass (e.g., ApiSecurityController) overrides actions() and does NOT merge with parent actions(), it loses the OPTIONS handler!
Make sure subclasses do:
public function actions()
{
return array_merge(parent::actions(), [
// any subclass-specific actions here
]);
}
OR do NOT override actions() if you don’t need to customize.
2. behaviors() method and CORS filter:
ApiBaseController should have CORS filter configured and applied correctly:
Ensure subclasses do NOT override behaviors() without merging parent's, which can remove the CORS filter.
Example subclass:
public function behaviors()
{
return array_merge(parent::behaviors(), [
// Add/override other behaviors if needed
]);
}
3. beforeAction() or other interceptors:
If your base or subclass controllers override beforeAction(), make sure:
They allow OPTIONS requests without throwing errors or blocking them.
A common pattern:
public function beforeAction($action)
{
if (\Yii::$app->request->method === 'OPTIONS') {
return true; // skip CSRF/auth for OPTIONS
}
return parent::beforeAction($action);
}
Otherwise, middleware or validation could prematurely reject OPTIONS requests.
4. Routing and URL Manager:
Check your URL rules and ensure the controllers extending ApiBaseController are matched properly.
Sometimes rules can specify HTTP verbs or limited patterns that exclude OPTIONS.
5. Debugging approach:
Temporarily disable beforeAction and complex auth/CSRF logic in ApiBaseController to isolate the issue.
Create a minimal version of the failing controller that only extends ApiBaseController and supports OPTIONS + CORS.
Send curl OPTIONS requests and analyze headers.
Compare with working TestController setup.
6. Summary of what to fix/check:
Checkpoint
What to do
actions() properly includes OPTIONS
In base controller; subclasses merge with parent if overridden
behaviors() includes CORS filter
In base controller; subclasses merge with parent if overridden
beforeAction() allows OPTIONS harmlessly
Return true immediately for OPTIONS requests
Routing allows OPTIONS requests
URL rules don't restrict HTTP verbs incorrectly
No conflicting logic in middlewares, filters
Temporarily disable/adjust to test
Example minimal ApiBaseController snippet:
class ApiBaseController extends Controller
{
public $enableCsrfValidation = false; // if you want manual CSRF
public function actions()
{
return [
'options' => [
'class' => \yii\rest\OptionsAction::class,
],
];
}
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::class,
'cors' => [
'Origin' => $this->getAllowedOrigins(),
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
'Access-Control-Allow-Headers' => ['Content-Type', 'Authorization', 'X-Requested-With', 'X-CSRF-Token'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 3600,
],
];
return $behaviors;
}
public function beforeAction($action)
{
if (\Yii::$app->request->method === 'OPTIONS') {
return true; // safely skip CSRF/auth for OPTIONS
}
return parent::beforeAction($action);
}
}
If after making sure all these points are satisfied, the CORS OPTIONS request still fails on controllers extending ApiBaseController but works on TestController, share:
The full code of your ApiBaseController.
The full code of the subclass like ApiSecurityController.
Any overridden methods actions(), behaviors(), beforeAction().
Your URL manager rules affecting these controllers.
We can spot the difference causing the issue.
In essence: The common trap is that subclass controllers override actions() or behaviors() and forget to merge parent config, causing the OPTIONS handler or CORS filter to disappear and OPTIONS preflight to fail with 405 or CORS errors.
If you want, I can help review your specific controllers side by side for these things!
// src/services/csrfServices.ts
import Cookies from 'js-cookie';
import apiClient from './apiClientServices';
import { ENDPOINTS } from '../constants/apiConstants';
import logger from '../utils/loggerUtils';
/**
CSRF Token manager class.
Handles fetching token from backend, reading from cookie,
caching token internally, and providing easy access.
On app startup, call:
await csrfTokenManager.init();
In your axios interceptor (or wherever you send API requests):
import { csrfTokenManager } from './csrfServices';
export type CsrfData =
{
csrfParam: string;
csrfToken: string;
};
/**
Fetch the CSRF token and param from the backend endpoint.
This triggers the backend to set the CSRF cookie.
Throws an error if token or param are missing.
*/
export async function fetchCsrfToken(): Promise
{
const response = await apiClient.get(ENDPOINTS.security.csrfToken);
const { csrfParam, csrfToken } = response.data;
if (!csrfParam || !csrfToken)
{
throw new Error('Failed to fetch CSRF token');
}
const cookieToken = getCsrfToken();
if (!cookieToken || cookieToken !== csrfToken)
{
throw new Error('CSRF token in cookie does not match token from backend response.');
}
return { csrfParam, csrfToken };
}
/**
Read the CSRF token directly from the CSRF cookie.
Returns undefined if cookie is missing.
*/
export function getCsrfTokenFromCookie(): string | undefined
{
return Cookies.get(CSRF_COOKIE_NAME);
}
class CsrfTokenManager
{
private csrfParam?: string;
private csrfToken?: string;
/**
* Initialize the token manager by fetching token from backend,
* and then synchronizing with the token in cookie.
* Call once on app startup.
*/
async init()
{
try
{
const { csrfParam, csrfToken } = await fetchCsrfToken();
this.csrfParam = csrfParam;
this.csrfToken = csrfToken;
}
catch (error)
{
logger.warn('csrfServices.ts', 'Could not fetch CSRF token from backend', error);
}
// Override with cookie token if available (more reliable/up-to-date)
const cookieToken = getCsrfTokenFromCookie();
if (cookieToken)
{
this.csrfToken = cookieToken;
}
}
/**
* Get the current CSRF token to be used for headers.
* Prefers cookie token if it exists, else falls back to cached token.
*/
getToken(): string | undefined
{
// Prefer cookie token if available (more up to date)
const cookieToken = getCsrfTokenFromCookie();
if (cookieToken)
{
this.csrfToken = cookieToken;
return cookieToken;
}
// Fall back to fetched token
return this.csrfToken;
}
/**
* Get the CSRF param name (cookie name / form param name).
*/
getParam(): string | undefined
{
return this.csrfParam;
}
}
// Export a singleton CSRF token manager instance to be used app-wide.
export const csrfTokenManager = new CsrfTokenManager();
this is my frontend code and how it handles csrf token, I keep having issues with:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/api-security/csrf-token. (Reason: CORS request did not succeed). Status code: (null).
I thought by extending the controller with the apiBaseController, the apiBaseController sets whats within it into
any controller that uses it, so i wouldnt need to add OptionAction::cass actions() to each controller? or public $enableCsrfValidation = false;
if these are already set in the apiBaseController
apiBaseController cors setup:
use Yii;
use yii\rest\Controller;
use yii\rest\OptionsAction;
use yii\web\BadRequestHttpException;
use yii\web\Response;
class ApiBaseController extends Controller
{
public function behaviors(): array
{
$behaviors = parent::behaviors();
/**
* Ip Rate Limiter Filter
* @url https://github.com/yiisoft/yii2/blob/master/framework/filters/RateLimitInterface.php
*
$behaviors['rateLimiter'] =
[
'class' => IpRateLimiter::class,
'rateLimit' => 10,// The maximum number of allowed requests
'timePeriod' => 60,// The time period for the rates to apply to
'separateRates' => false,// Separate rate limiting for guests and authenticated users
'enableRateLimitHeaders' => false,// Whether to return HTTP headers containing the current rate limiting information
];//*/
/**
* CORS Filter - placed before authenticator and content negotiation
* @url https://www.yiiframework.com/doc/guide/2.0/en/rest-controllers#cors
* @url https://www.yiiframework.com/doc/api/2.0/yii-filters-cors
*
* Note: This must be before the authenticator to allow OPTIONS preflight.
*/
$behaviors['corsFilter'] =
[
'class' => Cors::class,
'cors' => [
/**
* Allowed request origins - set via env variable or fallback default
* Frontend axios must have:
*
* axios.defaults.withCredentials = true;
*/
'Origin' => $this->getAllowedOrigins(),
/**
* Allowed HTTP methods in CORS preflight
* Can be overridden in child controllers to narrow methods per controller
*
* If left empty or not set here, 'Cors' defaults to all common HTTP verbs allowed.
*
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],//*/
/**
* Allowed HTTP headers clients can use during the actual requests.
* This should include Authorization for bearer tokens and other headers you expect.
*
* Common headers your React app will send are:
* - Authorization (for Bearer token)
* -- Your backend CORS must allow both 'Authorization' and 'Content-Type' in Access-Control-Allow-Headers.
* -- Also, 'OPTIONS' requests must bypass authentication for CORS
* preflight (see 'except' => ['options'] in authenticator behavior).
* - Content-Type (usually application/json)
* - X-Requested-With (sometimes added by libraries)
* - X-CSRF-Token (if using CSRF protection, mostly for stateful apps)
* - Accept (To ask API which format it supports) Often handled automatically, usually no CORS action needed
*
* Note: For native apps or SPAs that send JWT tokens via the Authorization: Bearer <token> header in AJAX/fetch requests,
* this header must be allowed by CORS to avoid preflight errors by the browser.
*/
'Access-Control-Allow-Headers' => ['Content-Type', 'Authorization', 'X-Requested-With', 'X-CSRF-Token'],
'Access-Control-Expose-Headers' => ['X-CSRF-Token'],
/**
* Allow credentials (cookies, HTTP auth, etc.) in requests
* When set to true, it allows the browser to expose the response to frontend JavaScript when
* credentials are included in the request.
*
* Note: Frontend must set withCredentials=true when sending request
*/
'Access-Control-Allow-Credentials' => true,
// Preflight OPTIONS request cache duration (seconds)
'Access-Control-Max-Age' => 3600,
],
];
return $behaviors;
}
public function actions()
{
return [
'options' => [
//'class' => OptionsAction::class,
'class' => '\yii\rest\OptionsAction',
],
];
}
protected function getAllowedOrigins(): array
{
$originsEnv = $_ENV['CORS_ORIGINS'] ?? getenv('CORS_ORIGINS') ?: '';
// Split into array, trim whitespace, remove empties
$origins = array_filter(array_map('trim', explode(',', $originsEnv)));
if (empty($origins))
{
// default origin for dev, adjust accordingly
$origins = ['http://localhost:1234'];
}
//\Yii::error("Allowed Origins: " . print_r($origins, true), __METHOD__);
return $origins;
}
}
Way I call it in other controllers:
final class ApiSecurityController extends ApiBaseController
{
public function behaviors(): array
{
$behaviors = parent::behaviors();
/**
* CORS Filter
* Override allowed HTTP methods for CORS preflight specifically for UserController
* Prevent 405 Cors access error with sending "OPTIONS"
*/
$behaviors['corsFilter']['cors']['Access-Control-Request-Method'] = ['GET', 'POST', 'OPTIONS'];
/**
* Authenticator Filter
* - Extend 'except' so signup and reset-password actions do not require auth
* - Ensure uniqueness after merge in case of duplicates
*/
if (!isset($behaviors['authenticator']['except']))
{
$behaviors['authenticator']['except'] = [];
}
$behaviors['authenticator']['except'] = array_merge(
$behaviors['authenticator']['except'], [
'csrf-token',
'refresh-jwt-token',
'options',// Add 'options' HTTP verb to skip auth for CORS preflight
]
);
// Remove duplicates just in case
$behaviors['authenticator']['except'] = array_unique(
$behaviors['authenticator']['except']
);
return $behaviors;
}
Thanks for the detailed code! Let's analyze why your ApiSecurityController (and potentially other controllers extending ApiBaseController) still have CORS preflight Issues / 405 errors, while your test controller with minimal setup works fine.
Summary of your setup:
ApiBaseController:
Defines behaviors() with CORS filter, setting allowed origins from env
Defines actions() returning the OPTIONS action
enableCsrfValidation disabled manually in your controllers (good for REST)
ApiSecurityController:
Overrides behaviors() calling parent::behaviors()
Modifies the 'Access-Control-Request-Method' array in the CORS filter config to include 'OPTIONS'
Extends authenticator behavior exceptions to skip CSRF, JWT, and OPTIONS for except
The most likely cause:
The actions() method is overridden — or missing OPTIONS in subclasses
You only defined actions() in ApiBaseController, and not in `ApiSecurityController**.
This is actually the right thing—ApiSecurityController inherits actions(), which defines OPTIONS action.
But: The problem can arise if:
You override actions() in ApiSecurityController and forget to call parent::actions() or forget to include OPTIONS.
Or if ApiBaseController is an abstract base that some controllers do not extend directly.
Or you have a custom URL rule or route configuration blocking OPTIONS.
Next check => your ApiSecurityController code
You pasted your behaviors method but not whether actions() is overridden.
If you have no actions() in ApiSecurityController it should inherit properly; if you override the method and return e.g. an empty array or without OPTIONS, your preflight breaks.
Additional things to troubleshoot & fix
1. Make sure actions() is NOT overridden or, if overridden, merges parent:
public function actions()
{
return array_merge(parent::actions(), [
// your additional actions if any
]);
}
2. Your CORS filter should be applied before authentication filters
Good, you already placed it first by calling parent::behaviors() and modifying it afterward.
But be sure to also include other HTTP verbs you might need (PUT, PATCH, DELETE) or simply do not override it unless necessary — the default includes common HTTP verbs:
Check if requests even reach your controller CORS filter.
Recommended minimal example for your ApiBaseController
class ApiBaseController extends Controller
{
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::class,
'cors' => [
'Origin' => $this->getAllowedOrigins(),
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
'Access-Control-Allow-Headers' => ['Content-Type', 'Authorization', 'X-Requested-With', 'X-CSRF-Token'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 3600,
],
];
// if you have auth filters, attach them here, but after corsFilter
return $behaviors;
}
public function actions()
{
return [
'options' => [
'class' => \yii\rest\OptionsAction::class,
],
];
}
public function beforeAction($action)
{
if (Yii::$app->request->method === 'OPTIONS') {
return true; // allow OPTIONS requests
}
return parent::beforeAction($action);
}
}
In your ApiSecurityController
final class ApiSecurityController extends ApiBaseController
{
// No need to override actions() or behaviors() unless you need custom behavior
public function behaviors()
{
$behaviors = parent::behaviors();
// Extend allowed HTTP methods if needed
$behaviors['corsFilter']['cors']['Access-Control-Request-Method'] = [
'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'
];
// Adjust authenticator exceptions for csrf-token or options actions if you have authentication behaviors
if (isset($behaviors['authenticator']) && !empty($behaviors['authenticator']['except'])) {
$behaviors['authenticator']['except'] = array_unique(array_merge(
$behaviors['authenticator']['except'],
['csrf-token', 'refresh-jwt-token', 'options']
));
}
return $behaviors;
}
}
Summary checklist
Common cause
Solution
Missing OPTIONS action in controller
Define or inherit actions() with OptionsAction
actions() overridden without merging
Use return array_merge(parent::actions(), [...])
CORS behavior overridden without merging
Use parent::behaviors() and merge CORS config appropriately
OPTIONS blocked by beforeAction
Allow OPTIONS early and return true in beforeAction()
Authenticator blocking OPTIONS
Add 'options' to exceptions in authenticator behavior
URL Manager blocks OPTIONS
Confirm URL rules allow OPTIONS method
If after checking all this you're still stuck, please share the full code of your ApiSecurityController and ApiBaseController including actions(), behaviors(), and beforeAction() methods, and your URL manager rules. That way I can help pinpoint exactly where the difference is.
Your beforeAction() implementation looks good in terms of allowing OPTIONS requests to bypass CSRF validation — which is a critical step to prevent 405 and CORS preflight failures.
A quick checklist on your beforeAction() method:
You correctly call parent::beforeAction($action) first and return false if it fails.
You explicitly check for OPTIONS HTTP method and return true early (skip validation).
For POST/PUT/PATCH/DELETE, you validate CSRF token from header or request body.
You throw BadRequestHttpException if the token validation fails.
The header name (X-CSRF-Token) matches exactly what your frontend sends.
The body param name (csrfParam) matches what your backend expects.
If you're receiving JSON bodies, confirm that getBodyParams() parses JSON correctly (I saw you configured JSON parser on the request component earlier, so this should be fine).
2. Exception class casing
You wrote:
throw new badRequestHttpException('Invalid CSRF token.');
The class should be:
throw new \yii\web\BadRequestHttpException('Invalid CSRF token.');
Make sure correct casing and namespace apply or it will cause a PHP error and return a 500.
3. Double-check parent::beforeAction()
If your parent controller has beforeAction() that blocks or validates things, ensure it allows OPTIONS to pass through as well.
If any parent beforeAction() triggers an exception or returns false on OPTIONS, this would cause issues.
4. Ensure this method is in the right controller(s)
If beforeAction() is only in some subclasses but not your base API controller, you might want to move or duplicate this logic consistently.
5. Consider auth checks
If you have authentication behaviors, confirm they don't interfere with OPTIONS requests. Usually auth behaviors should exclude OPTIONS too.
Summary:
Your current beforeAction() code already correctly skips CSRF validation for OPTIONS, which means:
Your CORS preflight requests won’t get blocked or rejected here.
You prevent 405 or 403 errors due to CSRF on OPTIONS preflight.
Make sure:
Exception class is correctly imported and capitalized.
<?php
namespace app\controllers\api;
use Yii;
use yii\rest\Controller;
use yii\filters\Cors;
use yii\web\BadRequestHttpException;
use yii\filters\auth\CompositeAuth;
class ApiBaseController extends Controller
{
public $enableCsrfValidation = false; // We do manual CSRF validation
/**
* Define which actions this controller supports,
* including OPTIONS handler for CORS preflight
*/
public function actions()
{
return [
'options' => [
'class' => \yii\rest\OptionsAction::class,
],
];
}
/**
* Configure controller behaviors
* - CORS configured dynamically based on allowed origins
* - Authentication added but excludes OPTIONS
*/
public function behaviors()
{
$behaviors = parent::behaviors();
// CORS filter: responds to OPTIONS preflight & adds CORS headers
$behaviors['corsFilter'] = [
'class' => Cors::class,
'cors' => [
'Origin' => $this->getAllowedOrigins(),
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
'Access-Control-Allow-Headers' => [
'Content-Type',
'Authorization',
'X-Requested-With',
'X-CSRF-Token',
],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 3600,
// Add more directives if needed
],
];
// Example auth filter (replace with your own)
$behaviors['authenticator'] = [
'class' => CompositeAuth::class,
'except' => ['options'], // Skip authentication on OPTIONS requests (CORS preflight)
'authMethods' => [
// add your auth methods here (HttpBearerAuth, etc.)
],
];
return $behaviors;
}
/**
* Manual CSRF token validation (because enableCsrfValidation=false)
* - Allows OPTIONS requests freely (no CSRF validation)
* - For POST, PUT, PATCH, DELETE, validates token in header or body
*/
public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
$request = Yii::$app->request;
if ($request->method === 'OPTIONS') {
// OPTIONS (preflight) requests do not require CSRF check
return true;
}
if (in_array($request->method, ['POST', 'PUT', 'PATCH', 'DELETE'], true)) {
$token = $request->headers->get('X-CSRF-Token');
if (!$token) {
$params = $request->getBodyParams();
$token = $params[$request->csrfParam] ?? null;
}
if (!$request->validateCsrfToken($token)) {
Yii::warning('Invalid CSRF token for request to ' . $request->url);
throw new BadRequestHttpException('Invalid CSRF token.');
}
}
return true;
}
/**
* Get allowed origins from environment variable or fallback
* Return an array of allowed origins for CORS
*/
protected function getAllowedOrigins(): array
{
$originsEnv = $_ENV['CORS_ORIGINS'] ?? getenv('CORS_ORIGINS') ?: '';
$origins = array_filter(array_map('trim', explode(',', $originsEnv)));
if (empty($origins)) {
// Adjust defaults as needed for local development
$origins = ['http://localhost:3000', 'http://localhost:1234'];
}
return $origins;
}
}
Refactored ApiSecurityController.php
<?php
namespace app\controllers\api;
use Yii;
/**
* Example API Controller extending ApiBaseController
* Supports CSRF token endpoint as well as other security-related endpoints
*/
final class ApiSecurityController extends ApiBaseController
{
/**
* We don't need to override actions() unless adding custom actions,
* options action is inherited and works fine.
*/
/**
* Override behaviors() **only if extending or modifying behaviors**,
* careful to merge parent's behaviors!
*/
public function behaviors()
{
$behaviors = parent::behaviors();
// If you want to customize corsFilter config:
if (isset($behaviors['corsFilter']['cors'])) {
$behaviors['corsFilter']['cors']['Access-Control-Request-Method'] = ['GET', 'POST', 'OPTIONS'];
// You can adjust Access-Control-Allow-Headers here if needed
}
// Extend authenticator exceptions if you have certain actions open
if (isset($behaviors['authenticator']) && isset($behaviors['authenticator']['except'])) {
$behaviors['authenticator']['except'] = array_unique(array_merge(
$behaviors['authenticator']['except'],
['csrf-token', 'refresh-jwt-token', 'options'] // actions without auth required
));
}
return $behaviors;
}
/**
* Example action returning CSRF token info + sets CSRF cookie.
* Your frontend calls this API to initialize CSRF token.
*/
public function actionCsrfToken()
{
$request = Yii::$app->request;
if (!$request->isGet) {
throw new \yii\web\BadRequestHttpException('Only GET requests allowed.');
}
$token = $request->getCsrfToken();
// Set CSRF cookie explicitly with required flags:
Yii::$app->response->cookies->add(new \yii\web\Cookie([
'name' => $request->csrfParam,
'value' => $token,
'httpOnly' => false, // Must be false so frontend JS can read it
'secure' => YII_ENV_PROD, // true if using HTTPS in prod
'sameSite' => YII_ENV_PROD ? \yii\web\Cookie::SAME_SITE_NONE : \yii\web\Cookie::SAME_SITE_LAX,
]));
return [
'csrfParam' => $request->csrfParam,
'csrfToken' => $token,
];
}
}
Additional notes for configuration
Frontend must send withCredentials: true in axios/fetch to send cookies cross-origin.
Your backend environment variable CORS_ORIGINS ideally set like:
is important if your frontend JavaScript needs to read the X-CSRF-Token header from backend responses.
Why include Access-Control-Expose-Headers?
By default, browsers only expose a limited set of response headers to frontend JavaScript because of the CORS security model. These are called "simple response headers" (Cache-Control, Content-Language, Content-Type, etc.).
If your backend sends custom headers like X-CSRF-Token and you want the frontend code to read them via JavaScript (e.g., via xhr.getResponseHeader() or in fetch response headers), you must explicitly expose them by setting Access-Control-Expose-Headers in your CORS response.
When does this matter for your CSRF setup?
If your backend sends the CSRF token in the X-CSRF-Token response header (some APIs do that, for example after login or token refresh), and your frontend wants to read this header, you must expose it.
Otherwise, JS cannot read that header from the browser’s CORS response (it will be silently hidden).
Why did I omit it in my example?
Your initial code snippet included it correctly.
I focused on the minimal required headers to solve your preflight and CORS errors.
If your current backend does not send X-CSRF-Token in the response header, or your frontend does not need to access it from response headers, then it's optional.
But if your frontend does consume CSRF tokens from response headers, you should keep it.
How to restore it?
Simply add it back inside the cors array in your CORS filter, like this:
Keep 'Access-Control-Expose-Headers' => ['X-CSRF-Token'] in your backend CORS config if your frontend JavaScript reads the CSRF token from that response header.
Otherwise, it can be omitted if unused.
Let me know if you want help verifying whether your backend sends this header and how your frontend reads CSRF tokens!
Great question—let me clarify the role of Access-Control-Expose-Headers and who needs it, whether it's native React apps or web browsers.
What does Access-Control-Expose-Headers do?
This CORS response header tells the browser which response headers are accessible to JavaScript (e.g., fetch or XMLHttpRequest APIs) running in the frontend app.
By default, browsers hide most response headers from JavaScript for security reasons. Only a set of simple headers like Content-Type are accessible automatically.
If you want frontend JS to be able to read custom headers, e.g., X-CSRF-Token, the server must explicitly expose them with Access-Control-Expose-Headers.
Who benefits from Access-Control-Expose-Headers?
Any web frontend app running in a browser that needs to read custom response headers will require this header.
This includes browser-based React apps, Angular, Vue, vanilla JS, etc.
It is not limited only to native React (React Native) apps — in fact, React Native apps run outside of browser environments and do not enforce CORS or related browser security constraints.
They do not need this header because CORS is a browser security feature, and React Native (or other native apps) do not have those limitations.
So:
If your web browser app communicates with the backend and wants to read custom response headers, yes, you must setAccess-Control-Expose-Headers to include those headers.
If you don't expose those headers, your JS code will not be able to access the header value, even though the header was sent by the server.
How does this apply to X-CSRF-Token?
If your backend sends X-CSRF-Token as a response header, and your frontend JavaScript reads (e.g., to update the token from server after auth or refresh), this header must be exposed.
The cookie-based CSRF token can be read from cookies, but sometimes apps send/refresh tokens via headers.
If your frontend never reads this header from the response, or if you rely only on CSRF token cookies (readable via JS with HttpOnly: false), then exposing that header is not required.
Summary:
Environment
Need Access-Control-Expose-Headers for custom headers like X-CSRF-Token?
Browser-based React SPA
Yes, if frontend reads token from response headers
React Native (native apps)
No, since no browser CORS restrictions
Other native mobile apps
No, same reason as React Native
Plain web form apps (server rendered)
Usually no, because tokens are embedded in HTML or handled differently
TL;DR
Access-Control-Expose-Headers is for web browsers to allow JS to access custom response headers.
Native React apps do not use CORS or need this header.
Your web browser React app needs it only if it reads X-CSRF-Token or any custom header from the server responses.
If you do not read or use the X-CSRF-Token response header in your React app — and instead get tokens via cookie or initial JSON body — you can safely omit this header from CORS.
If you want, I can review your React frontend code or help you decide whether you actually need to expose this header or not!
Yes, your idea is valid and touches on a defense-in-depth approach that can help mitigate CSRF and certain XSS risks.
Recap of your idea:
Send the CSRF token via both:
a cookie (usually HttpOnly: false so JavaScript can read it), and
a custom response header (e.g., X-CSRF-Token).
On the client side:
Store the token in memory (e.g., React state or a JS variable), separate from cookie.
When submitting forms or making API calls, compare the token from memory against the cookie token.
Only proceed if both tokens match or fulfill your validation criteria.
How this can help:
1. Additional CSRF Token Validation
Having the token in two places (cookie + JS memory) means an attacker must compromise both to forge a valid request.
The cookie is sent automatically by the browser, but your frontend only sends the token from memory (or uses it to sign the request).
If an attacker manages to steal only the cookie (via some XSS exploit or other means), they still need access to your in-memory token to construct valid requests — which may be harder.
2. Mitigating Some XSS Risks
Because the token is stored in memory and not, for example, in localStorage or persistent cookies, it is cleared on page reload or navigation.
This reduces the time window for an attacker who obtains your JS context to reuse stolen tokens.
In-memory storage generally protects against long-lived XSS leak attacks that steal stored tokens from persistent storage.
3. Double-Submit Cookie Pattern
Your approach resembles a variant of the classic double-submit cookie pattern:
A CSRF token is stored in a cookie (sent automatically).
The same token is sent explicitly in a header or form field.
Backend validates that the token in the header matches the token in the cookie.
This helps prevent CSRF because malicious third-party sites cannot set or read your cookies, so they cannot produce a matching header token.
Implementation Notes
On the server/backend:
Validate that the CSRF token sent in the header matches the CSRF token cookie.
Reject requests where they differ.
This prevents forged requests without the token in both places.
On the client/frontend:
Fetch CSRF token from backend once (via JSON or header).
Store it in memory for your app session.
Read the cookie token with JS from document.cookie or a cookie utility.
When making API calls, ensure the header token is the in-memory token.
Optionally, verify cookie and memory token match on your frontend (can detect tampering).
Advantages:
Adds a layer of complexity for an attacker.
Makes stealing a usable CSRF token harder because attacker needs access to both cookie and in-memory token.
If implemented with secure handling and careful XSS mitigation, it strengthens your app's CSRF and XSS protection.
Limitations & considerations:
You still must protect against XSS vulnerabilities to keep your frontend JS context trusted.
If attacker fully controls JS execution (severe XSS), all tokens accessible to JS are vulnerable.
Using HttpOnly cookies for CSRF tokens (in combination with backend-side validation logic) can mitigate some JS access, but then frontend cannot read cookie — you trade off convenience.
This pattern increases frontend complexity — the code must stay in sync with backend validation.
In short
Your idea of:
Sending token via header and cookie
Maintaining a token in memory
Validating token integrity between memory and cookie on client AND matching tokens on server
is indeed a sound strategy and aligns with defense-in-depth CSRF strategies like double-submit cookie with extra client-side validation, which can help reduce risk of CSRF and mitigate some XSS attack vectors.
Final advice
If you implement this:
Ensure strict backend validation of the two tokens matching.
Prevent token leakage or exposure to JS where possible.
Keep the in-memory token lifecycle tightly controlled (clear on logout/navigate).
Couple this with robust XSS defenses—CSP, input sanitization, no inline scripts, etc.
If you want, I can help you sketch code examples (backend validation logic + frontend memory vs cookie validation) for this approach!
You're absolutely right to question the practical security benefit of this approach versus its complexity. Let's break down the realistic security posture of your idea and the considerations:
1. CSRF Token in Memory vs Cookie — What Does This Really Buy You?
CSRF tokens are designed to prevent unauthorized cross-site requests, leveraging the same-origin policy and the fact that attackers cannot read or set cookies from another origin.
Your idea to hold the token in memory (JS variable) and compare it to the cookie token adds a client-side double-check. But:
Both the in-memory token and the cookie are accessible to JavaScript.
This means if an attacker manages to execute malicious JavaScript (an XSS attack), they can read both tokens.
The attacker can trivially read the in-memory token and the cookie token and produce a valid request.
Since both values are readable by JS, the attacker gaining JS execution essentially breaks any client-side secrecy.
Also, because the token is in memory only, it disappears on refresh, so you need to fetch the token frequently — adding complexity and potential availability concerns.
2. Primary Purpose of CSRF Token
The core defense is leveraging the Same Origin Policy and the inability of an attacker-controlled third-party site to read your cookies or tokens.
The backend expects the CSRF token to be in the request header or body, and that it must match the valid token stored server-side (often in the user session).
This prevents attackers from forging requests, because they cannot read or guess the secret token.
3. The Real Security Risk: XSS
XSS is the root problem if an attacker can just read your client-side tokens.
If an attacker can run arbitrary JavaScript in your page, tokens stored as cookies readable by JS or in-memory are vulnerable.
In that case, your extra client-side complexity won’t stop the attacker.
Preventing XSS is fundamental: sanitizing inputs, setting Content Security Policy (CSP), secure frameworks, minimizing unsafe eval/inline scripts, etc.
4. Is Your Idea Worth It Then?
Technically it adds no cryptographically significant increase in security against a capable XSS attacker.
It adds client-side complexity in synchronizing tokens, fetching them often, and comparing them.
It may help detect some minor token tampering bugs or issues, but from a pure security perspective, it doesn't stop a sophisticated attack.
The simplest and most effective CSRF defense is:
Use CSRF tokens generated securely and validated server-side.
Store tokens in cookies with correct SameSite and Secure attributes.
Make sure those tokens are sent back via headers or forms on affected requests.
Rely on browser security to prevent other sites from reading your cookies.
Prevent XSS fully to protect token confidentiality.
5. When Would Your Idea Help?
If you expect non-malicious bugs or mis-synchronizations that cause different tokens client-side vs cookie, your double-check might catch logic errors.
In app architectures where tokens are managed partly client-side and partly server-side dynamically, having sync checks may help.
But this is mostly defense-in-depth, not a guarantee against attackers.
Summary
Consideration
Your approach (double token)
Reality/Effort
Protection against CSRF
Present, but no more than standard CSRF token
Same as usual, server-side validation is key
Protection against XSS
Nil (JS can read both tokens)
Need proper XSS prevention instead
Complexity added
Increased client-side complexity for token sync
May cause bugs, harder maintenance
Token freshness
Requires frequent fetching due to memory volatility
Network overhead, latency
Real security value
Limited beyond standard CSRF measures
Focus on secure configs & XSS is better use of effort
Final advice
Keep your CSRF tokens simple, secure, and validated on server.
Use a consistent way to send/store tokens (cookie + header or JSON).
Implement strong XSS defenses.
Use SameSite=Lax/Strict cookies and HTTPS.
Avoid unnecessary client-side token juggling.
If you want, I can help simplify your CSRF flow to best practice without over-complication, ensuring solid security and ease of maintenance. Would that help?
On the backend, validate the token against what’s stored in the user's session or server-side state.
This approach leverages:
The browser enforcing same-origin policy so attackers cannot read or forge tokens.
Server-side token validation, which keeps the token secret and safe.
Secure cookie options (Secure, SameSite) that minimize exposure and CSRF risks.
Why this is good enough:
CSRF attacks rely on the attacker tricking the browser to send authenticated requests without the token. Since they cannot read or set your cookies or tokens, they cannot guess or include the correct token.
XSS attacks, which can compromise tokens, must be mitigated separately via input sanitization, CSP, and secure JS practices.
When you might want to add complexity:
Your app requires advanced token rotation or multi-layer security.
Your tokens must be shared securely across different domains or contexts.
You want to reduce JS-read token exposure (e.g., enforcing HttpOnly cookies).
Your architecture is heavily SPA-based with complex token flows.
But for most cases—and especially if you want safe, maintainable security—the cookie + backend validation + standard CSRF token approach works well and is simpler.
In summary:
✅ Use CSRF token cookie + strong server-side validation
✅ Ensure secure cookie flags (Secure, SameSite) where possible
✅ Frontend sends token in header or form field
✅ Protect your app robustly against XSS
✅ Avoid unnecessary client-side token juggling
If you want, I can assist with concrete examples or reviewing your current setup to ensure this is implemented correctly and securely!
If X-CSRF-Token is not listed in that response:
The browser blocks the actual request, throwing a CORS error.
Your AJAX call fails before it reaches the server.
When can you omit 'X-CSRF-Token' from allowed headers?
If you never use the X-CSRF-Token header in your frontend AJAX requests (e.g., you send CSRF token only via cookies or form fields).
But usually modern frontend frameworks and best practices include the CSRF token in a header like X-CSRF-Token for REST APIs.
Summary
Keep 'X-CSRF-Token' in Access-Control-Allow-Headers if you send it from frontend JS.
It's part of enabling your frontend to send requests with that custom header across origins.
Omitting it causes CORS preflight failures.
If you want, I can help review your frontend requests to confirm if you actually need this header allowed or not.
X-CSRF-Token
No need to include it
This header only controls what frontend is allowed to send, so it is strictly about front-end → back-end communication.
If you want, I can also explain how to verify and test your frontend headers and backend CORS config!
The frontend JavaScript can send these headers (including X-CSRF-Token) to your backend.
The frontend JavaScript can also read the X-CSRF-Token header from the backend response.
Summary table:
Header
Direction
Purpose
Access-Control-Allow-Headers
Backend → browser (preflight)
Which request headers frontend JS may send
Access-Control-Expose-Headers
Backend → browser
Which response headers frontend JS may access
So yes, your understanding is correct and matches best practices!
Let me know if you want examples on how to set these on the backend or how to handle them in your frontend code!
Certainly! Here's a concise example showing:
How to configure headers on the backend for CORS, including Access-Control-Allow-Headers and Access-Control-Expose-Headers
How to configure Axios on the frontend to send and receive CSRF tokens correctly
1. Backend — Yii2 CORS config snippet
Inside your controller (or base controller) behaviors method:
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::class,
'cors' => [
'Origin' => $this->getAllowedOrigins(), // e.g. ['http://localhost:3000']
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
'Access-Control-Allow-Headers' => [
'Content-Type',
'Authorization',
'X-Requested-With',
'X-CSRF-Token', // <-- Allow this header from frontend in requests
],
'Access-Control-Expose-Headers' => [
'X-CSRF-Token', // <-- Allow frontend JS to read this header from response
],
'Access-Control-Allow-Credentials' => true, // Allow cookies/auth credentials
'Access-Control-Max-Age' => 3600,
],
];
return $behaviors;
}
2. Frontend — Axios setup example
This example assumes you have a csrfTokenManager to fetch/store the CSRF token but the key points here are:
Tell Axios to send cookies on cross-origin requests (withCredentials: true)
Add the CSRF token header to every request using an interceptor
import axios from 'axios';
import { csrfTokenManager } from './csrfServices'; // your CSRF token helper
// Tell Axios to send cookies (credentials) for cross-origin requests
axios.defaults.withCredentials = true;
// Axios request interceptor to inject CSRF token header
axios.interceptors.request.use(config => {
const csrfToken = csrfTokenManager.getToken();
if (csrfToken) {
config.headers['X-CSRF-Token'] = csrfToken;
}
return config;
}, error => {
return Promise.reject(error);
});
3. Using Axios to GET CSRF token from backend
On app startup, call your backend endpoint to get the CSRF token and set the cookie and internal memory:
async function initializeCsrfToken() {
try {
const response = await axios.get('/api/api-security/csrf-token');
const { csrfParam, csrfToken } = response.data;
// The backend should set the CSRF token cookie in response automatically
// You can store it in memory for faster access if you like
csrfTokenManager.setToken(csrfToken);
csrfTokenManager.setParam(csrfParam);
} catch (error) {
console.error('Failed to initialize CSRF token', error);
}
}
// Call initializeCsrfToken at app startup
initializeCsrfToken();
Summary
Backend header
Purpose
Access-Control-Allow-Headers
Allow frontend to send these headers
Access-Control-Expose-Headers
Allow frontend JS to read these headers in response
Access-Control-Allow-Credentials
Allow cookies and auth info to be sent
Frontend Axios config
Purpose
withCredentials: true
Include cookies in requests
interceptors.request.use(...)
Add X-CSRF-Token header automatically
Fetch CSRF token on startup
Initialize and keep CSRF token up to date
If you'd like, I can provide a minimal full working example project setup or snippets tailored for your exact needs!
// src/services/csrfServices.ts
import Cookies from 'js-cookie';
import apiClient from './apiClientServices';
import { ENDPOINTS } from '../constants/apiConstants';
import logger from '../utils/loggerUtils';
/**
CSRF Token manager class.
Handles fetching token from backend, reading from cookie,
caching token internally, and providing easy access.
On app startup, call:
await csrfTokenManager.init();
In your axios interceptor (or wherever you send API requests):
import { csrfTokenManager } from './csrfServices';
export type CsrfData =
{
csrfParam: string;
csrfToken: string;
};
/**
Fetch the CSRF token and param from the backend endpoint.
This triggers the backend to set the CSRF cookie.
Throws an error if token or param are missing.
*/
export async function fetchCsrfToken(): Promise
{
const response = await apiClient.get(ENDPOINTS.security.csrfToken);
const { csrfParam, csrfToken } = response.data;
if (!csrfParam || !csrfToken)
{
throw new Error('Failed to fetch CSRF token');
}
const cookieToken = getCsrfToken();
if (!cookieToken || cookieToken !== csrfToken)
{
throw new Error('CSRF token in cookie does not match token from backend response.');
}
return { csrfParam, csrfToken };
}
/**
Read the CSRF token directly from the CSRF cookie.
Returns undefined if cookie is missing.
*/
export function getCsrfTokenFromCookie(): string | undefined
{
return Cookies.get(CSRF_COOKIE_NAME);
}
class CsrfTokenManager
{
private csrfParam?: string;
private csrfToken?: string;
/**
* Initialize the token manager by fetching token from backend,
* and then synchronizing with the token in cookie.
* Call once on app startup.
*/
async init()
{
try
{
const { csrfParam, csrfToken } = await fetchCsrfToken();
this.csrfParam = csrfParam;
this.csrfToken = csrfToken;
}
catch (error)
{
logger.warn('csrfServices.ts', 'Could not fetch CSRF token from backend', error);
}
// Override with cookie token if available (more reliable/up-to-date)
const cookieToken = getCsrfTokenFromCookie();
if (cookieToken)
{
this.csrfToken = cookieToken;
}
}
/**
* Get the current CSRF token to be used for headers.
* Prefers cookie token if it exists, else falls back to cached token.
*/
getToken(): string | undefined
{
// Prefer cookie token if available (more up to date)
const cookieToken = getCsrfTokenFromCookie();
if (cookieToken)
{
this.csrfToken = cookieToken;
return cookieToken;
}
// Fall back to fetched token
return this.csrfToken;
}
/**
* Get the CSRF param name (cookie name / form param name).
*/
getParam(): string | undefined
{
return this.csrfParam;
}
}
// Export a singleton CSRF token manager instance to be used app-wide.
export const csrfTokenManager = new CsrfTokenManager();
Is my token manager good enough for this? or would you refactor it?
Your CsrfTokenManager is quite solid and follows good patterns:
It fetches the CSRF token from backend via API.
It reads the CSRF token cookie.
It caches the token internally.
It exposes methods for getting the token and param.
The init() method tries to sync between backend response token and cookie token.
Overall, the main strengths:
Fetching token at app startup ensures the backend sets the proper CSRF cookie and returns the token in JSON.
Preferring the cookie token for subsequent usage is good because the cookie reflects what browser sends with requests.
Graceful error logging if fetch fails.
Clear separation of responsibility.
Possible improvements & suggestions
Rename getCsrfToken() vs getCsrfTokenFromCookie():
You have getCsrfTokenFromCookie() but call getCsrfToken() inside fetchCsrfToken() — make sure consistency in naming to avoid confusion.
Avoid redundant fetching on every init:
Your current init() fetches from the backend and then immediately reads the cookie token and overwrites, possibly with a different token. This is fine but you might consider:
Fetching from backend only when cookie is missing or expired.
Or having the backend always set the cookie and your frontend trusts the cookie unless there's an error.
Add a setter for tokens (optional):
If you ever want to update tokens manually (e.g., on refresh), exposing setters might be helpful.
Concurrency / multiple calls:
If multiple parts of your app call init(), consider guarding against duplicated fetches with a simple flag or promise cache.
Type safety and null safety:
Your typing is good with string | undefined, which is great for TS.
Extract token from Set-Cookie headers (rarely needed):
Typically you rely on the browser storing cookies, but if you want to be bulletproof, you might check HTTP response headers for Set-Cookie and parse tokens (usually unnecessary).
Add comments specifying security assumptions:
Note that your tokens are visible to JS because cookie is non-HttpOnly, so take care with XSS.
Example refactor with a few minor improvements (optional):
class CsrfTokenManager {
private csrfParam?: string;
private csrfToken?: string;
private initPromise?: Promise<void>;
// Initialize once
async init(): Promise<void> {
if (this.initPromise) return this.initPromise;
this.initPromise = (async () => {
try {
const { csrfParam, csrfToken } = await fetchCsrfToken();
this.csrfParam = csrfParam;
this.csrfToken = csrfToken;
} catch (error) {
logger.warn('csrfServices.ts', 'Could not fetch CSRF token from backend', error);
}
// Update token from cookie if available (more reliable)
const cookieToken = getCsrfTokenFromCookie();
if (cookieToken) {
this.csrfToken = cookieToken;
}
})();
return this.initPromise;
}
getToken(): string | undefined {
const cookieToken = getCsrfTokenFromCookie();
if (cookieToken) {
this.csrfToken = cookieToken;
return cookieToken;
}
return this.csrfToken;
}
getParam(): string | undefined {
return this.csrfParam;
}
// Optional setter if you want to manually update tokens
setToken(token: string, param?: string): void {
this.csrfToken = token;
if (param) this.csrfParam = param;
}
}
Final thoughts:
Your current implementation is good enough and efficient for typical SPA use cases.
Minor enhancements above improve concurrency and clarity.
Remember to build your app with proper XSS mitigations since token is exposed to JS.
Make sure your backend and cookie configs (SameSite, Secure flags) are correct, as this manager depends on the cookie being properly set.
If you want me to review your API that serves the token or give a full end-to-end example, I can help with that too!
const apiClient = axios.create({
baseURL: API_BASE_URL,
withCredentials: true,// sends cookies automatically with cross-origin requests
headers:
{
'Content-Type': 'application/json',
},
timeout: 10000,// Aborts the request and throws an error after 10 seconds
});
apiClient.interceptors.request.use(
async (config: AxiosRequestConfig) =>
{
// TODO - Frontend (React/Axios) need to:
// read token from the non-HttpOnly cookie or from csrf-token endpoint
// add X-CSRF-Token header to mutating requests (POST, PUT, PATCH, DELETE)
const token = csrfTokenManager.getToken();
if (token)
{
config.headers['X-CSRF-Token'] = token;
}
// src/services/signupService.ts
import apiClient from './apiClientServices';
import { ENDPOINTS } from '../constants/apiConstants';
//import { CsrfData } from '../../services/csrfServices';
import type { GenericResponse } from '../types/signupApiTypes';
export type CsrfData =
{
csrfParam: string;
csrfToken: string;
};*/
export interface SignupStageZeroEmailResponseData
{
//userId: number;// If expecting userId to be returned from backend
signupPhase: number;
nextPhase?: number;
// other fields if any
}
export async function submitSignupStageZeroEmail(
data: SignupStageZeroEmailData,// This argument becomes HTTP request body (JSON)
csrf: CsrfData,// This argument is used to set HTTP header for CSRF token
//userId?: string | number,// optional userId param for adding to URL
): Promise<GenericResponse>
{
const postData =
{
...data,
// If you want to include CSRF token in body instead of header, could do:
//[csrf.csrfParam]: csrf.csrfToken,
};
const response = await apiClient.post(
/**
* Option to add data to the URL
* @see app\src\constants\apiConstants.ts
*
* stageZeroEmail: (userId: number | string) => `api-signup/stage-zero-email/?id=${userId}`,
*
ENDPOINTS.signup.stageZeroEmail(userId),//*/
ENDPOINTS.signup.stageZeroEmail,// URL (constant, no params included by default)
postData,// Request Body (serialized JSON)
/**
* Api Client Services handles sending csrf token
*
{
headers:
{
'X-CSRF-Token': csrf.csrfToken
},
}*/
);
// Return the 'data' part of the backend response
return response.data;
}
Your setup looks pretty well structured and mostly follows best practices for CSRF handling with Axios in a React + Yii2 environment. Here are some comments and small suggestions:
1. apiClientServices.ts — Axios instance and interceptor
withCredentials: true correctly ensures cookies are sent cross-origin if applicable.
The interceptor properly reads the CSRF token from your csrfTokenManager and adds it as X-CSRF-Token header.
The interceptor runs on every request — this might be slightly inefficient if you want to send the CSRF header only on mutating requests (POST, PUT, PATCH, DELETE). You can optimize:
You call apiClient.post and you rely on your Axios interceptor to add the CSRF token header automatically — good separation of concerns.
You have commented option to add CSRF to request body via:
//if you want to include CSRF token in body instead of header:
//[csrf.csrfParam]: csrf.csrfToken,
Typically, it’s better to send it in the header as you do currently. Sending in body is sometimes necessary for non-ajax forms or certain legacy set-ups, but for APIs headers are more standard.
3. Passing csrf as a parameter to submitSignupStageZeroEmail
In your current code, the csrf parameter is accepted but not used explicitly, since Axios interceptor attaches it automatically.
You can remove the csrf argument from this function unless you want to inject CSRF token in the body explicitly.
Alternatively, if you want to keep it, consider using it consistently, e.g.:
Signup Stage Zero EMail Response Data - Expected return body (JSON)
The data you expect to receive from the backend response after submitting stage zero:
Includes server-generated identifiers like userId and possibly the current signup phase.
*/
export interface SignupStageZeroEmailResponseData
{
//userId: number;// If expecting userId to be returned from backend
signupPhase: number;
nextPhase?: number;
// other fields if any
}
export async function submitSignupStageZeroEmail(
data: SignupStageZeroEmailData,// This argument becomes HTTP request body (JSON)
//csrf: CsrfData,// This argument is used to set HTTP header for CSRF token
//userId?: string | number,// optional userId param for adding to URL
): Promise<GenericResponse>
{
const postData =
{
...data,
// If you want to include CSRF token in body instead of header, could do:
//[csrf.csrfParam]: csrf.csrfToken,
};
const response = await apiClient.post(
/**
* Option to add data to the URL
* @see app\src\constants\apiConstants.ts
*
* stageZeroEmail: (userId: number | string) => `api-signup/stage-zero-email/?id=${userId}`,
*
ENDPOINTS.signup.stageZeroEmail(userId),//*/
ENDPOINTS.signup.stageZeroEmail,// URL (constant, no params included by default)
postData,// Request Body (serialized JSON)
/**
* Api Client Services handles sending csrf token
*
{
headers:
{
'X-CSRF-Token': csrf.csrfToken
},
}*/
);
// Return the 'data' part of the backend response
return response.data;
}
I left the option if I wanted to use it:
signupService.ts usage
You call apiClient.post and you rely on your Axios interceptor to add the CSRF token header automatically — good separation of concerns.
You have commented option to add CSRF to request body via:
//if you want to include CSRF token in body instead of header:
//[csrf.csrfParam]: csrf.csrfToken,
Typically, it’s better to send it in the header as you do currently. Sending in body is sometimes necessary for non-ajax forms or certain legacy set-ups, but for APIs headers are more standard.
But I am already sending it inside the apiClientServices.ts
apiClient.interceptors.request.use(
async (config: AxiosRequestConfig) =>
{
/**
* Read token from the non-HttpOnly cookie or from csrf-token endpoint
* add X-CSRF-Token header to mutating requests (POST, PUT, PATCH, DELETE)
*/
const method = config.method ? config.method.toLowerCase() : '';
if (['post', 'put', 'patch', 'delete'].includes(method))
{
const token = csrfTokenManager.getToken();
if (token)
{
config.headers['X-CSRF-Token'] = token;
}
}
What you have:
Your signupService.ts API call sends the request body without manually setting CSRF tokens.
Your apiClientServices.ts Axios instance automatically adds the X-CSRF-Token header on mutating requests (POST, PUT, PATCH, DELETE) via the interceptor, reading from csrfTokenManager.getToken().
You keep the commented option in signupService.ts to manually add CSRF token in the body if ever needed, but you do not need to do this with your current architecture.
Why this is good:
Separation of concerns:
API call code doesn't care about CSRF tokens — tokens are handled transparently in the Axios interceptor.
Centralized token management: csrfTokenManager abstracts fetching, caching, and providing current CSRF token.
Standard practice for REST APIs:
Sending X-CSRF-Token header is the recommended approach for CSRF protection in AJAX APIs.
Just a couple of reminders / tips:
Keep your interceptor efficient:
Your code only adds CSRF token header on mutating methods which is great.
No need to pass CSRF token in function calls:
Since token setting is automatic, you can clean up your API functions by removing CSRF parameters as you did.
If you ever need to support legacy form submissions:
You can use your commented option to add the token in request body/form data.
Make sure that your backend expects X-CSRF-Token header and properly validates it alongside cookie tokens.
import apiClient from './apiClientServices';
import { ENDPOINTS } from '../constants/apiConstants';
export interface SignupStageZeroEmailData {
email: string;
}
export interface SignupStageZeroEmailResponseData {
signupPhase: number;
nextPhase?: number;
}
export async function submitSignupStageZeroEmail(
data: SignupStageZeroEmailData
): Promise<GenericResponse<SignupStageZeroEmailResponseData>> {
// No csrf parameter here
const response = await apiClient.post(ENDPOINTS.signup.stageZeroEmail, data);
return response.data;
}
2. Explicitly passing CSRF token to the API call (if you want to control it manually)
signupService.ts
import apiClient from './apiClientServices';
import { ENDPOINTS } from '../constants/apiConstants';
import type { CsrfData } from './csrfServices';
export interface SignupStageZeroEmailData {
email: string;
}
export interface SignupStageZeroEmailResponseData {
signupPhase: number;
nextPhase?: number;
}
export async function submitSignupStageZeroEmail(
data: SignupStageZeroEmailData,
csrf: CsrfData
): Promise<GenericResponse<SignupStageZeroEmailResponseData>> {
const response = await apiClient.post(
ENDPOINTS.signup.stageZeroEmail,
data,
{
headers: {
'X-CSRF-Token': csrf.csrfToken, // explicitly set header here
},
}
);
return response.data;
}
Usage example somewhere in your React app:
import { csrfTokenManager } from './csrfServices';
import { submitSignupStageZeroEmail } from './signupService';
async function signup(email: string) {
// Initialize or get CSRF token before making request
await csrfTokenManager.init();
const csrf = {
csrfParam: csrfTokenManager.getParam() ?? 'csrfToken',
csrfToken: csrfTokenManager.getToken() ?? '',
};
const response = await submitSignupStageZeroEmail({ email }, csrf);
console.log('Signup response:', response);
}
Summary
Approach
CSRF header added by
API call signature
When to use
1. Axios interceptor only
Axios interceptor transparently
No csrf param needed
Recommended & cleanest
2. Explicit CSRF param passing
Manually in API call headers
Pass csrf token param to API functions
Useful for fine-grained control
If you want, I can help you refactor your codebase to consistent one approach and cleanup!
// src/components/Site.tsx
import React, { useEffect, useRef } from 'react';
import { Routes, Route } from 'react-router';
import { csrfTokenManager } from '../services/csrfServices';
import { AlertProvider, useAlert } from '../hooks/useAlertHooks';
import { useEventListener } from '../hooks/useEventListenerHooks';
import '../styles/Site.css';
import Header from './site/Header';
import Content from './site/Content';
import Footer from './site/Footer';
import Faq from './site/Faq';
import Login from './site/Login';
import Signup from './site/Signup';
const SiteContent = () =>
{
// Get showAlert function from context
const { showAlert, dismissAlert, alerts } = useAlert();
// Use a ref to store alert IDs so the array persists across renders
const alertIds = useRef<number[]>([]);
function handleAlert(event: CustomEvent<{ type: string; message: string }>)
{
const detail = event.detail;
if (detail?.type && detail?.message)
{
const alertId = showAlert(detail.type, detail.message);
alertIds.current.push(alertId);
}
}
// Use your custom event listener hook for 'alert' event
useEventListener('alert', handleAlert);
useEffect(() =>
{
async function init()
{
await csrfTokenManager.init();// fetch CSRF token & cookie
}
init();
}, []);
The AxiosError: Network Error usually means the request never reached the backend or was blocked by the browser due to CORS/security reasons or networking issues.
From your logs:
AxiosError: Network Error
and the call stack shows it happened during fetchCsrfToken() call inside your React app's SiteContent component during initialization.
Common reasons and things to check:
1. Backend Server is not reachable or wrong URL
Make sure your backend API server is running and accessible at the URL your apiClient is configured with (API_BASE_URL).
If your React app runs at http://localhost:1234 and your backend server is e.g., on http://localhost:5000, then the baseURL config in Axios should point exactly to http://localhost:5000.
If the backend is down or the URL mismatches, network errors occur.
2. CORS Preflight/Policy Blocking
Since your frontend and backend are on different origins/ports (:1234 vs :5000), browsers will enforce CORS.
If your backend is not responding correctly to CORS preflight OPTIONS request, this can cause network errors.
Check your backend logs and verify CORS headers are properly sent and OPTIONS requests handled (status 200).
3. Wrong or missing environment variable API_BASE_URL
Verify your API_BASE_URL variable is correctly set in your frontend build environment.
If it's undefined or incorrect, Axios will try to send requests to invalid URLs and fail.
4. Proxy or Firewall
If using npm start dev server (React), consider setting up a proxy to route /api calls to your backend.
Alternatively, configure backend to accept requests from your frontend's origin, with proper CORS (your Yii2 config).
How to troubleshoot your code specifically:
Confirm API_BASE_URL
Open console in browser, add:
console.log('API_BASE_URL:', API_BASE_URL);
Make sure it prints the expected backend URL (e.g., http://localhost:5000).
if (!csrfParam || !csrfToken)
{
throw new Error('Failed to fetch CSRF token');
}
const cookieToken = getCsrfTokenFromCookie();
if (!cookieToken || cookieToken !== csrfToken)
{
throw new Error('CSRF token in cookie does not match token from backend response.');
}
return { csrfParam, csrfToken };
}
why would the token be different?
Great progress! The error:
Error: CSRF token in cookie does not match token from backend response.
means that the token you read from the cookie (cookieToken) does not match the token the backend returned in the JSON response (csrfToken).
Why might the tokens be different?
1. The cookie token is stale or from a previous request/session
The cookie sent to the frontend might be an older token from a previous session or a cached cookie value.
The backend getCsrfToken() generates the current valid token for this request.
Since your frontend reads the cookie before backend updated it or after a token rotation, tokens differ.
2. The cookie is not set yet at the time you read it
Cookies are set via Set-Cookie header in the response of your /csrf-token endpoint.
Your JavaScript client reads document.cookie immediately after receiving the JSON response. However, the cookie may not be available in document.cookie yet because:
Browsers update document.cookie asynchronously after processing response headers.
If you read the cookie too early, it might still hold the old value or be empty.
3. Cookie path or domain differs
If the cookie path or domain is set improperly, the browser may not send the cookie back or may be reading a cookie with a different path/domain.
Double-check that path or domain attributes are either unset (default) or consistently set so your frontend JS can read the cookie value correctly.
4. HTTP vs HTTPS and secure flag
If your environment is production (YII_ENV_PROD), you set secure: true on the cookie.
If you're testing locally on http, the cookie will not be set/sent.
This causes your JS to fail reading the cookie token (undefined or old), causing mismatch.
5. Multiple cookies with similar names
Sometimes multiple cookies with the same name but different paths or domains can exist.
Browser sends one cookie per scope; you might be reading or sending another cookie than what the backend expects.
6. Proxy or CORS issues
If you access backend via a proxy or different origin, cookies might be blocked or stripped.
Why does the token keep growing everytime i refresh?
Cookie “csrfToken” is invalid because its size is too big. Max size is 4096 B. 2 csrf-token
(2025-05-23T17:28:16.502Z) [csrfServices.ts] Token from backend response: JwL4mbi4HBz5Q3GA5GD27zdAS83-tomV6399lweNdYNRu9X_DpJaPw9C0__xN8ZIJ7mZ25bLkm_8tpNh6rF34fl2vOlg71NBWCK-MWbFlG4C4v_mq_2pi-6ypL7Lx-xs7BzwUogvHjs4bDXnJiJuaTx0vIgixOENbo_f6rNggtY-HXuz3rN8okY3wTm70lDrp15ViaADBgU2WVu3eub2ED9muSuX8ehIwNHAvaMN8u-0UiEekJJCTOw1ZhIidkR5ctEPxQfZC6x1c5WyiM_0ZtayW1nPmL0iQVQcwNaTJ-HQ3cQoKnAz84E1b0WIicN4jFXyV0yXLng_xFRIG224zaYjg1ijmcngBFYxEOqnaX13wkPeYWRwCiZkROTFiRb3adMMk0Bhu5fuLM6MHmJASj0ildknJWgPAlc7RCHeF3mpaRBoIW9qc7EZCmbIZVFKVApTr_sJ96QxBE6tQOYPKxNA4dDbzVF4clFzfQhnkFev7ItYxkOEm4XBCFCA7sepHEurPWJwTTfyEQ5GaoZ-aS2CsJBhUKbdYakSzOzKSrFRqGZWS1n29WLlLZs6rTaJJnPy0wNdADmU6c6JY7mRngJVMoQe377U9YHpdbKPQzBfvJiRepwxKCg92x96ZPm9aHbBQUI8SyA6oNpRjZRhvEB3UNZy6_k-LeRQo4xFOwR-hLRKLiu3zxyxr-JwJUszIo3X1FZO4xe4JG0rdNavI6E48QU2IgqdHIp6DS8Sg_qSqKSm-iTEYX5ih1SRX0HYxeefc-NBVu3xuBtOOwURbXVfjXKX6Z5jODoIxoYMDstcHvFVrOFwCsArK_7gXUZNFxsDCSWA7xiKpAFvRIt3hA62-odCMffjt4lKZmaiii_dVahlt27tsM98wxX6bdgnXcqvNhJR8f_BhhGWh6Av63YeCN7aMFlSGmd0OCBWL4CY8GXfkYqJUg4YsrjuM12ZfatsNxmaWXKywspduZSslArdFBQHs_clhIzEG8dX7isL5UHN0Okv0AChlhpdzFw7X2r7-iuvwA9GrNGQNysHxqEkxtSZuy70NektajsDTwn5NU2X8OvvTeBd1URaAV8lNPUqIAojDvJjg4SDOStfpQay9b22i2_nH4m4BvREHi5Wu-DsIwVp06Xgtc0qEM0OXrcxrUvIn9piHcsSzov21afcx0QK7YOBABlrKRFwUXfWBfwgG_4TohGw-N5NZAnT0CUn2SvI1rwuxZeM58CH2UE_1uB0mTFbZfQ9U3ZKD8fibbQ1Fx9W_GnWc_xk1EmoMd1cG5HmRVcqrlsdwLLjW6liKBggdPoMbTZ136tAE5JQU6VBWJP2Kqa8lYFlA9ZSSee79XWyuX0yLG9D9NT7LNk5vTIJqxVbfY2wwgDwI3ZgitLsqALJfb-MuJm9D4fLeE-oUSVq4uP9oASCjdH7ZZIXenfCogTbA_ttuOCke35sFkK8Xw-dRKBHJb1AIZ3AHIeTFIvk60s4OZVJqi-JcudnLOcawOulHjb5OuwZYGuhymDmfir_082Tu60Vql0F_lOWIGIGe3BVSshxtDl0ore9BbVHFvOqJC9BlDGFNlKSFj7LJ7Wc2oasFWr9GfvHhdMA9cwUosjgKRx0qoUaF_uPyID_u1kaD7swpP06hBZjxIhOU9j2gWL82DY3TaGX4Luyr9rlQuxQ5uHsprfgf0jiSuJAGCj2ekyssBVfHBKs8Vw6toh99Y1chMkBCrHM-QyJSGY68Y6bJUfPwy8ISigLdo7wlEuXgX0nSfQwGg0fC2NXrdkQqCR9snMXK4iwzlpIXNyURKh6K0LcKDAUCZTq4lyUfr1b2-uInEF55GlhqsvRRfy7jpBQnJ0A_sHl646XJuGjUoLfcJbR6hUaK5SSBvYxmeOiiB-tGbvWTqT_g52z937s-Xs1wy1Dmyu5TCZXAAlmZMFmjvhtesWM9F6iBFPYYroVyFiuo_JayC7XS6yM6vpIPKH5rZy_DNLrEhBWurK3DI6jpwbCZvyxJy1aIAIgrlil6iQ3-d9sDQ8J1CkpYQxyCVVee-UITcKEjLayTgSIfzKPgNlZd0gExITBOa5RS47HsOP6rdzXML6jYKFxTbZh-iXcHWQ5t2vtMjECdBoCGzEH_eK_vApvz4D9nfJvR_qeg449aEGiA_iHhNyd6qIozP0Dts8tP1b8224Hb5Tfh8H0kUiNnuqYCYB6AxVEB2Nx8MTn0p9j8W8-VA0h9ua5sWwHPLYI0v_imsalEsdCEFh3Yb73345VXYoiMOi-I7Gnfg0Eoo_ZwfCMRwTkQ_05xAX9gLB0-mgNYQ2FiZpw6w1WiKu42YPaXaTf8jWS90O4vzTErlfbHyJrE49UEPzlI0jRt9XhtZvAp-bP9qWMtFyPaZIU8m0ocWEifoxcVz8qaR7y2nuIkEIY94iD4CTaunBICYDm9DrnL122ePmxabKKOAP_80FJdl8bMsEdi4B-dTPxefu6pBn2nZP0xzuFgIIDVG3T-XUJinlWQ3MXABdCskuhbJ5n-0M-wPrYuMwgnsQXNfbJ8m04BVCLneFTtuiR8EFOI3qc5AIuNNnYlirDB7MRPf5HC26cLg0sXPC9_ESxINHfrqpVB1BbhNAcMTGBdOkAJh9MQ0kMqp3bZ6ALmXvHNxvT3Zsdn7lsBCgFd0DxnBB6Pk5bOlcIcpNyCOMAYCAZAwBC2lYzLoUNaQY6WCLFnWyD8HlTG-QoqGFHShOGhen7HTcXJRIkfSzyFtu_5xuuM7bpy4h-Gsavgsh5LugEMjcrYMNpYmtd8Dgkd_rS1lk0464OxEKO1Jt6gRDuUyAaLqCqINBl-lPJe-piQcrlRzMtceeBq-0P0PTONgZC9W-A8JujsI0m395ufG33yegCzFpLcEi8czg-jvsLLqwCcHt4eE_1iyvo3wSKNgMFmwiNqXxL1gbV5i9aNDrP635-eu29SMbOgxF_elZv4fqNPi-qTfdIGVEQ5upsmHa7dHEXZdZLyU46eHPKzdmdyJSLHYAQNwHRHP8dc4201thBqiY51LrqbwRMR0MjMxDMIeCn2lRzQFiV50JFiW1KrjL-tSc-h15jsI0bPCFWcWc9ZrKcVf7TakID4R_JXcaw_idYwpf5vD0MS8C5Q4wK51zcJ4zJujOCXa8kjVAw5-RVYymBuq78UuzU-
The core issue here is that your CSRF cookie (csrfToken) keeps growing, eventually exceeding the browser limit (~4KB). The browser warning
Cookie “csrfToken” is invalid because its size is too big. Max size is 4096 B.
indicates that your cookie is repeatedly being set with longer and longer values — likely because every time you call the CSRF token endpoint, you’re setting a new cookie without clearing or replacing the old one properly, or the token itself is very large.
Why is this happening?
CSRF token generated by Yii getCsrfToken() is quite long, especially if you use a strong, random token (common in Yii2).
Multiple cookies with the same name but different attributes (path/domain) can get set, making the browser concatenate them or treat them incorrectly.
The CSRF cookie is being set again and again on each call to actionCsrfToken(), possibly no old cookie is cleared, or the frontend makes multiple calls unnecessarily.
How to fix and debug:
1. Confirm that your backend sets the CSRF cookie properly:
You should only set the cookie once, or you must replace the value, not append.
Make sure you’re not calling this endpoint multiple times rapidly or causing multiple cookies to be set on client accidentally.
2. Check for multiple CSRF cookies with different paths, domains, or flags
Open your browser DevTools → Application tab → Cookies.
Look for multiple cookies named csrfToken or whatever your CSRF cookie is named, but with different domain/path/flags.
If you find duplicates, some browsers treat cookies with same name but different scope as independent cookies and may send all of them, confusing your app and increasing total cookie size.
Solution:
Be explicit about cookie path and domain when setting cookie to avoid unintended duplicates.
If after this you still see cookie size growing or more than one cookie, please share a screenshot or copy-paste cookies from browser DevTools for further investigation!
−
>
cookies−>
add(newCookie([′name′=>
If you already configured the CSRF cookie settings globally in your web config under the request component like this:
'request' => [
'csrfCookie' => [
'httpOnly' => false,
'secure' => YII_ENV_PROD ? true : false,
'sameSite' => YII_ENV_PROD ? Cookie::SAME_SITE_NONE : Cookie::SAME_SITE_LAX,
'path' => '/', // <-- important if set here
],
// ...
],
Then you do NOT need to manually set the CSRF cookie again in your controller action using:
Yii2 automatically sets the CSRF cookie for you with your global config settings when you call $request->getCsrfToken() or enable CSRF validation.
Your controller does not need to manually reset or duplicate the cookie unless you have a very specific reason.
The global config ensures the cookie is set with consistent flags (sameSite, secure, path), avoiding duplicate cookies or mismatches.
When would you still need manual cookie setting?
If you want to force reset the CSRF cookie manually, e.g., after login/logout or token refresh beyond default behavior.
If you want to set it in an API endpoint without usual Yii CSRF validation flow (some REST API flows).
If you want to customize the cookie per request in a way the global config can't.
In your case
Since you already have csrfCookie configured globally with appropriate flags including 'path' => '/' (or you add it there), your backend will set the CSRF cookie automatically.
Your /csrf-token endpoint can just return the token JSON without manually adding cookie.
public function actionCsrfToken(): array
{
$request = Yii::$app->request;
if (!$request->isGet) {
throw new BadRequestHttpException('Only GET allowed.');
}
$token = $request->getCsrfToken();
// *** No need to set cookie manually here ***
return [
'csrfParam' => $request->csrfParam,
'csrfToken' => $token,
];
}
Important note:
Do confirm that your csrfCookie in web config includes 'path' => '/' (very important for cookie overwriting and consistent sending).
If omitted, cookie might get set with default path of the request, causing multiple cookies.
TL;DR:
Condition
Do you need to manually set CSRF cookie in controller?
Global csrfCookie config exists
No, Yii handles it automatically
No global config or custom logic
Yes, you might have to set it manually
You want to reset token explicitly
Yes, manual cookie set possible and acceptable
If you want, I can help you verify or improve your full Yii CSRF cookie global config file!
Example of corrected fetchCsrfToken() function
export async function fetchCsrfToken(): Promise<CsrfData> {
const response = await apiClient.get(ENDPOINTS.security.csrfToken);
const { csrfParam, csrfToken } = response.data;
if (!csrfParam || !csrfToken) {
throw new Error('Failed to fetch CSRF token');
}
const cookieToken = getCsrfTokenFromCookie(); // assign first
if (!cookieToken || cookieToken !== csrfToken) { // then use
throw new Error('CSRF token in cookie does not match token from backend response.');
}
return { csrfParam, csrfToken };
}
Double-check your code around line 58 in csrfServices.ts to confirm variable declarations come before usage.
If you want, you can provide your current fetchCsrfToken() function code and I can help identify exactly where the issue is.
// src/services/csrfServices.ts
import Cookies from 'js-cookie';
import apiClient from './apiClientServices';
import { ENDPOINTS } from '../constants/apiConstants';
import logger from '../utils/loggerUtils';
/**
CSRF Token manager class.
Handles fetching token from backend, reading from cookie,
caching token internally, and providing easy access.
On app startup, call:
await csrfTokenManager.init();
In your axios interceptor (or wherever you send API requests):
import { csrfTokenManager } from './csrfServices';
/**
* Initialize the token manager by fetching token from backend,
* and then synchronizing with the token in cookie.
* Call once on app startup.
*/
async init(): Promise<void>
{
if (this.initPromise)
{
return this.initPromise;
}
this.initPromise = (async () =>
{
try
{
const { csrfParam, csrfToken } = await fetchCsrfToken();
this.csrfParam = csrfParam;
this.csrfToken = csrfToken;
}
catch (error)
{
logger.warn('csrfServices.ts', 'Could not fetch CSRF token from backend', error);
}
// Override with cookie token if available (more reliable/up-to-date)
const cookieToken = getCsrfTokenFromCookie();
if (cookieToken)
{
this.csrfToken = cookieToken;
}
})();
return this.initPromise;
}
/**
* Get the current CSRF token to be used for headers.
* Prefers cookie token if it exists, else falls back to cached token.
*/
getToken(): string | undefined
{
// Prefer cookie token if available (more up to date)
const cookieToken = getCsrfTokenFromCookie();
if (cookieToken)
{
this.csrfToken = cookieToken;
return cookieToken;
}
// Fall back to fetched token
return this.csrfToken;
}
/**
* Get the CSRF param name (cookie name / form param name).
*/
getParam(): string | undefined
{
return this.csrfParam;
}
/* Optional setter if you want to manually update tokens
setToken(token: string, param?: string): void
{
this.csrfToken = token;
if (param)
{
this.csrfParam = param;
}
}//*/
}
// Export a singleton CSRF token manager instance to be used app-wide.
export const csrfTokenManager = new CsrfTokenManager();
this is my csrfServices.ts
logger.log('csrfServices.ts', 'Token from backend response:', csrfToken);
logger.log('csrfServices.ts', 'Token from cookie:', cookieToken); // <-- HERE
const cookieToken = getCsrfTokenFromCookie(); // <-- declared AFTER usage
How to fix:
You must declare and initialize cookieToken before trying to log or use it.
Corrected version of your fetchCsrfToken() function:
export async function fetchCsrfToken(): Promise<CsrfData> {
const response = await apiClient.get(ENDPOINTS.security.csrfToken);
const { csrfParam, csrfToken } = response.data;
await new Promise(resolve => setTimeout(resolve, 50)); // 50ms delay to let cookie set
if (!csrfParam || !csrfToken) {
throw new Error('Failed to fetch CSRF token');
}
// Declare cookieToken BEFORE using it:
const cookieToken = getCsrfTokenFromCookie();
logger.log('csrfServices.ts', 'Token from backend response:', csrfToken);
logger.log('csrfServices.ts', 'Token from cookie:', cookieToken);
if (!cookieToken) {
throw new Error('CSRF token cookie missing.');
}
if (cookieToken !== csrfToken) {
throw new Error('CSRF token in cookie does not match token from backend response.');
}
return { csrfParam, csrfToken };
}
Summary:
Always declare variables before you use them.
In this case, move const cookieToken = getCsrfTokenFromCookie(); before the logger.log statements that reference it.
The 50ms delay is likely to help ensure the browser has set the cookie when you then read it.
This fix will eliminate the ReferenceError.
One extra recommendation
You may want to write your log lines after the essential validations to avoid logging undefined or confusing states, e.g.:
const cookieToken = getCsrfTokenFromCookie();
if (!cookieToken) throw new Error(...);
logger.log(...);
if (cookieToken !== csrfToken) throw new Error(...);
logger.log(...);
If you want, I can help you with a fully cleaned-up version or anything else!
The key log lines:
Token from backend response: FuOAwLzINPvrLl8qFaKGXvVXMfYyxK2bd2cY7PHaJntvlbj164NSjtpfK31N2_IuwmdArFSy7qJBX1CUs58XIw==
Could not fetch CSRF token from backend Error: CSRF token in cookie does not match token from backend response.
suggest your frontend is receiving a CSRF token (from backend JSON response) different from what’s stored in the cookie (csrfToken cookie).
Why?
1. The CSRF token cookie you read is outdated or different token from what backend expects.
Your backend’s getCsrfToken() generates a token (usually stored server-side in session), which is sent as JSON response AND set as cookie via Set-Cookie.
Cookies are updated asynchronously, so your frontend reading the cookie immediately after the API call may get the old token or none.
The 50ms delay might not be sufficient or consistent in your environment.
2. Your frontend reading the cookie token and the returned backend token are out of sync.
If the backend regenerates a token per request (getCsrfToken() sometimes does), the token in the JSON response can differ from the token of the previous request (the previous cookie).
3. Your backend config might regenerate CSRF token on every call
Yii2’s default getCsrfToken() can generate a different token every time you call it depending on session state.
If your session not persisted or multiple tokens generated, the cookie and returned token not matching.
Suggested fix steps:
Option 1: Trust backend token only and remove cookie token comparison
Since cookie reading can be delayed/inconsistent, modify fetchCsrfToken() to trust backend token:
export async function fetchCsrfToken(): Promise<CsrfData> {
const response = await apiClient.get(ENDPOINTS.security.csrfToken);
const { csrfParam, csrfToken } = response.data;
if (!csrfParam || !csrfToken) {
throw new Error('Failed to fetch CSRF token');
}
// Optionally read cookie but do not throw if mismatch
const cookieToken = getCsrfTokenFromCookie();
logger.log('csrfServices.ts', 'Token from backend response:', csrfToken);
logger.log('csrfServices.ts', 'Token from cookie:', cookieToken);
if (!cookieToken) {
logger.warn('csrfServices.ts', 'CSRF token cookie missing, continuing trusting backend token');
}
// **Do not throw if cookieToken !== csrfToken.**
// Just trust the backend token here.
return { csrfParam, csrfToken };
}
Option 2: Use only cookie token in frontend (simplify)
Since CSRF cookies are sent with every request, you can rely on the cookie as the source of truth:
Configure your backend session and CSRF behavior to:
Not regenerate the token on every request unless expired.
Store token persistently in session.
This is usually default Yii2 behavior unless customized.
How to check token consistency server-side:
On backend, log Yii::$app->request->getCsrfToken() calls to see if it changes across requests.
Check session handling proper and persistent.
Summary:
Problem
Suggested fix
CSRF token cookie and response differ
Trust backend response token only and optionally log cookie
Inconsistent tokens per request
Ensure stable backend CSRF token generation
Race condition reading cookie
Avoid compare or add delay/retry or just trust backend token
If you want I can help with:
Backend recipe to stabilize CSRF tokens in Yii2
Frontend code adjustments to trust token source
Improving your csrfTokenManager accordingly
Just ask!
//await new Promise(resolve => setTimeout(resolve, 50));// 50ms delay
if (!csrfParam || !csrfToken)
{
throw new Error('Failed to fetch CSRF token');
}
// Declare cookieToken BEFORE using it:
const cookieToken = getCsrfTokenFromCookie();
if (!cookieToken)
{
throw new Error('CSRF token cookie missing.');
}
logger.log('csrfServices.ts', 'Token from backend response:', csrfToken);
if (cookieToken !== csrfToken)
{
throw new Error('CSRF token in cookie does not match token from backend response.');
}
logger.log('csrfServices.ts', 'Token from cookie:', cookieToken);
return { csrfParam, csrfToken };
}
Your reasoning makes sense! If you’ve checked your backend logs and confirmed that the CSRF tokens returned in the JSON response match the tokens in the cookie, then the comparison should not throw unless there’s a bug in the code.
Let's carefully review your fetchCsrfToken implementation and identify possible subtle issues.
Your current function (reformatted for clarity):
export async function fetchCsrfToken(): Promise<CsrfData>
{
const response = await apiClient.get(ENDPOINTS.security.csrfToken);
const { csrfParam, csrfToken } = response.data;
if (!csrfParam || !csrfToken)
{
throw new Error('Failed to fetch CSRF token');
}
// Read cookie BEFORE logging
const cookieToken = getCsrfTokenFromCookie();
if (!cookieToken)
{
throw new Error('CSRF token cookie missing.');
}
logger.log('csrfServices.ts', 'Token from backend response:', csrfToken);
if (cookieToken !== csrfToken)
{
throw new Error('CSRF token in cookie does not match token from backend response.');
}
logger.log('csrfServices.ts', 'Token from cookie:', cookieToken);
return { csrfParam, csrfToken };
}
Things to check and suggestions:
1. Ordering of log statements
Right now you log backend token before logging cookie token, and the error CSRF token in cookie does not match is thrown before logging cookie token values.
So you don't see which values differ if there’s a mismatch.
Proposed fix: Log both tokens before any comparison or error thrown.
logger.log('csrfServices.ts', 'Token from backend response:', csrfToken);
logger.log('csrfServices.ts', 'Token from cookie:', cookieToken);
if (!cookieToken) {
throw new Error('CSRF token cookie missing.');
}
if (cookieToken !== csrfToken) {
throw new Error(`CSRF token in cookie (${cookieToken}) does not match token from backend response (${csrfToken}).`);
}
This way you get precise insight on the values you’re comparing.
2. Check for hidden differences in token strings
Tokens might look similar but differ subtly because of:
Leading/trailing whitespace
URL encoding differences (+ vs -, _ vs /)
Case differences (tokens are usually case sensitive, but worth verifying)
You can normalize tokens to make comparison cleaner:
const normalizedCookieToken = cookieToken.trim();
const normalizedCsrfToken = csrfToken.trim();
if (normalizedCookieToken !== normalizedCsrfToken) {
throw new Error(`CSRF token in cookie (${normalizedCookieToken}) does not match token from backend response (${normalizedCsrfToken}).`);
}
3. Ensure you are reading the correct cookie
Double check that CSRF_COOKIE_NAME (csrfToken) exactly matches the cookie your backend sets.
Unexpected cookie prefixes, domain/path mismatches, or multiple cookies might cause you to read a stale or wrong value.
4. Make sure cookie is fully set before you read it
Cookies can have slight delays in availability immediately after the response.
Try adding a short delay before reading cookie:
await new Promise(resolve => setTimeout(resolve, 50));
const cookieToken = getCsrfTokenFromCookie();
If this helps, the issue is a timing race.
5. Verify cookie storage/security flags
HttpOnly: false — required so JS can read
SameSite / Secure — must be compatible with your environment (dev/prod, http/https)
Full improved function with logs and normalization:
export async function fetchCsrfToken(): Promise<CsrfData> {
const response = await apiClient.get(ENDPOINTS.security.csrfToken);
const { csrfParam, csrfToken } = response.data;
if (!csrfParam || !csrfToken) {
throw new Error('Failed to fetch CSRF token');
}
// Optionally wait for cookie to be set
await new Promise(resolve => setTimeout(resolve, 50));
const cookieTokenRaw = getCsrfTokenFromCookie();
const cookieToken = cookieTokenRaw?.trim();
const backendToken = csrfToken.trim();
logger.log('csrfServices.ts', 'Token from backend response:', backendToken);
logger.log('csrfServices.ts', 'Token from cookie:', cookieToken);
if (!cookieToken) {
throw new Error('CSRF token cookie missing.');
}
if (cookieToken !== backendToken) {
throw new Error(`CSRF token in cookie (${cookieToken}) does not match token from backend response (${backendToken}).`);
}
return { csrfParam, csrfToken };
}
Final notes
Try these fixes and check logs carefully.
If tokens continue to mismatch, copy-paste exact logged token values to compare character-by-character or post here for help.
Consider that sometimes proxies, browser extensions, or dev tools can affect cookie behaviors.
Ensure no multiple cookies with same name but different paths/domains confuse your JS.
If you want, I can also help write a minimal repro with detailed logging that tracks token changes for you!
The log clearly shows the reason your tokens don’t match:
CSRF token from backend response: 54mJccSIrSINw09BDbJN2v1gCT_7uEITht21_wzbmeO48cg-lv7lGzS7BSV84RKqyiwwb5z6MkKxgsLMe6Hxrw==
CSRF token in cookie: 7914ed609a40a3df10e5b24985f6e22a4fa5e8496763dfb36a988d448c464447a:2:{i:0;s:9:"csrfToken";i:1;s:32:"_xAORvH99xJdqS_p7L9PgBpQ7_w3wzhL";}
What's going on?
Your JavaScript getCsrfTokenFromCookie() is reading a serialized PHP session cookie, and not the raw CSRF token string.
Explanation:
Your cookie is not the CSRF token cookie, but the PHP session cookie (PHPSESSID or equivalent).
That PHP session cookie stores the entire serialized PHP session data, which (among other things) contains the CSRF token inside the session.
So when you do Cookies.get('csrfToken') or whatever the cookie name, you are actually reading the session cookie, not the CSRF token cookie.
How to verify
Check in browser DevTools → Application → Cookies → you will see several cookies for your backend domain.
Typically, Yii2 PHP session cookie name is like PHPSESSID or custom, which stores serialized PHP session data (what you're reading).
Your CSRF cookie should be named according to your Yii2 config's csrfCookie.name (default is "csrfToken").
You are probably reading the wrong cookie name in your frontend.
Fix
1. Confirm the CSRF cookie name in your Yii2 backend config
Your logic is sound, the mismatch is due to reading the serialized session cookie incorrectly as the CSRF token.
Fix: Make sure your frontend reads only the CSRF cookie (csrfToken).
What about if you still read the serialized value?
If your frontend tries to read e.g. 'csrfToken' cookie but its value looks serialized, that means your backend is setting the wrong cookie value under that name or there's conflict.
Check if your backend csrfCookie config is correct
Ensure you aren’t accidentally setting session data with the same cookie name
Confirm no proxy or caching interferes
If you want, I can help you verify your Yii2 backend config and give you tested sample code!
Thanks for the clarification — you are reading exactly the cookie named 'csrfToken' in your frontend, which matches your Yii config’s CSRF cookie name.
However, the value stored in that 'csrfToken' cookie looks like serialized PHP session data, not the expected CSRF token string. So there's likely a mismatch between what the backend is setting as the CSRF cookie and what your frontend expects.
What’s likely happening?
Your Yii2 backend’s CSRF cookie is getting overwritten by the entire session cookie value, or you have a naming conflict.
Alternatively, your session cookie or some other cookie uses the same name 'csrfToken', causing confusion.
Your frontend is reading the cookie named 'csrfToken' as expected.
The content of that cookie is not a token but serialized PHP session data.
Likely cause: your session cookie has the same name ('csrfToken') as the CSRF token cookie.
Solution: Set different names for session and CSRF cookies in backend config, clear cookies, and retry.
If you provide your backend config for session and request components, I can quickly confirm or fix the cookie naming!
'request' => [
'class' => 'yii\web\Request',
/**
* Yii Csrf Protection
* @url https://www.yiiframework.com/doc/api/2.0/yii-web-request#$csrfCookie-detail
*
* Note: HttpOnly must be false. Doesn’t httpOnly = false make your cookie less secure?
* Yes, it means client-side scripts can read the cookie, but that is necessary here
* because your app needs to send the CSRF token on the header and validate requests.
*
* For CSRF tokens, this is common practice because:
* - The token itself is a cryptographically secure random string.
* - It's not a secret like a session id or auth token.
* - The cookie is scoped with proper SameSite and Secure attributes to limit risk.
*/
'enableCsrfValidation' => true,
'csrfParam' => '_csrf',// request param name
/**
* TODO <!-- Setup for live production.
* XSS Attacks Prevention - Sets the CSP header in the current response.
* See 'response' Restful Response Formatter below and set for production
*
* Note: Cross-Origin cookies require SameSite=None + Secure=true in *production*.
*/
'csrfCookie' => [
'name' => 'csrfToken',// cookie name you expect
/**
*'httpOnly' => false
* Setting httpOnly: false is necessary if your React app reads the CSRF token from
* the cookie via JavaScript (e.g., document.cookie) to include it in AJAX requests.
*
* However, this exposes the CSRF token cookie to JavaScript, which can be a slightly
* increased attack surface, so make sure you trust your frontend and avoid XSS
* vulnerabilities.
*
* Alternative approach is to deliver the CSRF token via a JSON payload response or
* HTTP header, avoiding cookie exposure — but if you prefer this route, httpOnly=false
* is fine.
*/
'httpOnly' => false,// Must be false so JS can read CSRF token
'secure' => YII_ENV_PROD ? true : false,// True if you use HTTPS in production
'sameSite' => YII_ENV_PROD ? Cookie::SAME_SITE_NONE : Cookie::SAME_SITE_LAX,
'path' => '/',// Ensure cookie always overrides previous cookies on all paths
],
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'gVrpH9LjNctQ4xgmVYcIq3LZlLKJeARz',
/**
* Yii Parsers
* The parse the request body as JSON if the client sends Content-Type: application/json. If a
* request comes with Content-Type: text/html or application/x-www-form-urlencoded, Yii will NOT
* use the JSON parser, and $request->post() and other usual methods behave normally.
*/
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
'session' => [
'class' => 'yii\web\Session',
'timeout' => 1440,// Session timeout in minutes; default is 1440 (24 hours)
//'name' => 'YOUR_SESSION_NAME',// Set a custom session name
/**
* TODO <!-- Setup for live production.
* Setup Session Cookies for Admin Access
*/
'cookieParams' => [
/**
* CookieParams (Development)
*/
'lifetime' => 0,// 0 means until the browser is closed
'domain' => '',// Domain for the cookie
'secure' => false,// Set to true if using HTTPS
'httponly' => true,// If true JavaScript can't access it, mitigating XSS risk
'samesite' => 'Lax',// Use 'Strict' or 'None' based on your needs
'path' => '/',// Ensure cookie always overrides previous cookies on all paths
//*/
/**
* CookieParams (Production)
*
'lifetime' => 0,
'domain' => '.example.com',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict',// or 'Lax' depending on your needs
'path' => '/',
],//*/
],
Thanks for sharing your config — everything looks correct and you have separate cookie names for CSRF and session cookies, which should prevent the issue of your CSRF cookie containing serialized session data.
Let’s summarize and troubleshoot why your csrfToken cookie contains serialized session-like data:
1. Confirm session cookie name
You did not explicitly set the session cookie name, so Yii2 defaults to PHPSESSID or equivalent depending on your PHP runtime.
Your session config shows:
'session' => [
'class' => 'yii\web\Session',
'timeout' => 1440,
// 'name' => 'YOUR_SESSION_NAME', <-- NOT set, so Yii/PHP default is used
'cookieParams' => [
...
'httponly' => true,
'path' => '/',
'samesite' => 'Lax',
'secure' => false, // or true in prod
],
],
The default session cookie name is NOTcsrfToken — so the serialized cookie you see named csrfToken is unexpected.
2. Are cookies getting mixed up somewhere?
The fact that your csrfToken cookie has serialized data means:
Either the backend is setting a session cookie with name csrfToken instead of PHPSESSID (config override or bug somewhere)
Or a different component (maybe a proxy or middleware) is overwriting the csrfToken cookie incorrectly
3. Verify all cookies for your domain with exact names and values
In browser dev tools → Application → Cookies
Check if:
Cookie named csrfToken contains the serialized value
Cookie named PHPSESSID (or other) exists normally
If you ONLY have csrfToken with serialized value and no normal session cookie with a different name, then the session cookie is probably configured (or accidentally overridden) to csrfToken, causing this problem.
4. Try explicitly setting a different session cookie name in config to isolate issue
Add a custom, unmistakable session cookie name (to separate it clearly from CSRF task):
If you want, you can share your apiClientServices.ts Axios config and your backend URL to validate them together. Also, I can help you with sample cURL commands to test backend connectivity.
Let me know if you want step-by-step debugging or working minimal repo example!
Your frontend is attempting to read the wrong cookie to get the CSRF token — it's reading the PHP session cookie value (_csrf) which stores serialized session data, not the CSRF token cookie.
The CSRF token is stored separately by Yii2 in a different cookie, usually named 'csrfToken' or as per your Yii configuration csrfCookie.name.
What should you do?
1. Check and confirm your Yii2 CSRF cookie settings
In your config, you have:
'csrfCookie' => [
'name' => 'csrfToken', // This is typically the default name for CSRF cookie
'httpOnly' => false,
/* other flags */
],
So the frontend should read the cookie named 'csrfToken' to get the actual CSRF token string.
2. Change your frontend to read the correct CSRF cookie
Currently, your frontend is reading the cookie named _csrf (the PHP session cookie), possibly by using this:
export const CSRF_COOKIE_NAME = '_csrf'; // probable mistake here
You need to change:
export const CSRF_COOKIE_NAME = 'csrfToken'; // MATCHES the backend config
Ensure your getCsrfTokenFromCookie uses this name:
export function getCsrfTokenFromCookie(): string | undefined {
return Cookies.get(CSRF_COOKIE_NAME); // Should get the csrfToken cookie now
}
3. Clear your browser cookies before testing
Especially clear cookies named _csrf and csrfToken and reload the app.
4. Verify cookies in the browser devtools
Open Application > Cookies in Chrome devtools.
Verify you have both:
A csrfToken cookie with the CSRF token string value.
A _csrf cookie with your PHP session serialized data.
Your app should read the csrfToken cookie.
Why does the csrfToken cookie exist alongside _csrf cookie?
_csrf is your session cookie that stores serialized PHP session data.
csrfToken is your CSRF token cookie containing only the random token string.
These two cookies serve different purposes and must not be confused.
Summary
What you read now
What you should read
_csrf cookie with serialized value
'csrfToken' cookie with string CSRF token
Example Fix:
// Change to match backend csrfCookie.name
export const CSRF_COOKIE_NAME = 'csrfToken';
export function getCsrfTokenFromCookie(): string | undefined {
return Cookies.get(CSRF_COOKIE_NAME);
}
After this, the token from cookie and token from backend JSON should match and your fetch-related errors will reduce/eliminate.
If you want, I can help review your full CSRF client-server flow to confirm everything is aligned!
// src/services/csrfServices.ts
import Cookies from 'js-cookie';
import apiClient from './apiClientServices';
import { ENDPOINTS } from '../constants/apiConstants';
import logger from '../utils/loggerUtils';
/**
CSRF Token manager class.
Handles fetching token from backend, reading from cookie,
caching token internally, and providing easy access.
On app startup, call:
await csrfTokenManager.init();
In your axios interceptor (or wherever you send API requests):
import { csrfTokenManager } from './csrfServices';
if (!cookieToken)
{
throw new Error('CSRF token cookie missing.');
}
logger.log('csrfServices.ts', 'Token from backend response:', csrfToken);
if (cookieToken !== backendToken)
{
throw new Error(CSRF token in cookie (${cookieToken}) does not match token from backend response (${backendToken}).);
}
logger.log('csrfServices.ts', 'Token from cookie:', cookieToken);
return { csrfParam, csrfToken };
}
/**
Read the CSRF token directly from the CSRF cookie.
Returns undefined if cookie is missing.
*/
export function getCsrfTokenFromCookie(): string | undefined
{
logger.log('All cookies via js-cookie:', Cookies.get());
/**
* Initialize the token manager by fetching token from backend,
* and then synchronizing with the token in cookie.
* Call once on app startup.
*/
async init(): Promise<void>
{
if (this.initPromise)
{
return this.initPromise;
}
this.initPromise = (async () =>
{
try
{
const { csrfParam, csrfToken } = await fetchCsrfToken();
this.csrfParam = csrfParam;
this.csrfToken = csrfToken;
}
catch (error)
{
logger.warn('csrfServices.ts', 'Could not fetch CSRF token from backend', error);
}
// Override with cookie token if available (more reliable/up-to-date)
const cookieToken = getCsrfTokenFromCookie();
if (cookieToken)
{
this.csrfToken = cookieToken;
}
})();
return this.initPromise;
}
/**
* Get the current CSRF token to be used for headers.
* Prefers cookie token if it exists, else falls back to cached token.
*/
getToken(): string | undefined
{
// Prefer cookie token if available (more up to date)
const cookieToken = getCsrfTokenFromCookie();
if (cookieToken)
{
this.csrfToken = cookieToken;
return cookieToken;
}
// Fall back to fetched token
return this.csrfToken;
}
/**
* Get the CSRF param name (cookie name / form param name).
*/
getParam(): string | undefined
{
return this.csrfParam;
}
/* Optional setter if you want to manually update tokens
setToken(token: string, param?: string): void
{
this.csrfToken = token;
if (param)
{
this.csrfParam = param;
}
}//*/
}
// Export a singleton CSRF token manager instance to be used app-wide.
export const csrfTokenManager = new CsrfTokenManager();
Your current csrfServices.ts looks well-structured and robust, handling CSRF token fetching, caching, and header injection appropriately.
A few final suggestions and confirmations to ensure smooth operation:
1. Cookie Name Consistency
You define CSRF_COOKIE_NAME = 'csrfToken', so make sure your backend Yii2 config for the CSRF cookie matches this exactly (which you stated is the case):
You correctly trim and compare the backend token and cookie token, then throw an error if mismatched.
Your logs will help diagnose any mismatch.
If you want to avoid errors in edge cases where cookie isn't updated immediately, you could optionally relax the check or add retries, but your strict approach is clearer for debugging.
3. Initialization Concurrency Control
Your initPromise prevents duplicated parallel requests to fetch the CSRF token — good practice.
4. Axios Interceptor Usage
You correctly inject the token on mutating HTTP methods only:
Make sure your app calls await csrfTokenManager.init() once on startup (which I see you do in your Site.tsx) so the token is ready before any API calls.
Optional Enhancements
You could add a retry or small delay in fetchCsrfToken() when reading the cookie in case of timing issues.
You could also provide setter methods in your token manager (commented out) if you want to manually update tokens in future flows.
Overall
This implementation:
Fetches CSRF token JSON and lets backend set cookie
Verifies cookie and response token match
Provides public getToken() for Axios interceptor use
Caches the token locally
Handles concurrency during init
If you encounter issues like token mismatch in future, start by checking cookies directly in browser devtools, and verify that backend and frontend cookie names and paths align perfectly.
You can confidently use this code for CSRF token management in your React + Yii2 app.
If you want, I can also help with example Axios setup or end-to-end flows!
if (token)
{
config.headers['X-CSRF-Token'] = token;
}
}
Why this works well:
Only mutating requests send the CSRF token header.
The token is fetched centrally from your csrfTokenManager.
withCredentials: true ensures cookies are always sent with the request (needed for session and CSRF cookie).
This interceptor keeps your API calls clean from repetitive CSRF logic.
Things to consider:
Make sure you call your csrfTokenManager.init()before any API calls to load the CSRF token and set the cookie properly.
If your API client might be used before the CSRF token is initialized, handle such cases carefully to avoid missing tokens.
Consider adding a response interceptor as needed for error handling (e.g., token expired, refresh, etc.).
If you want, I can help you with the full usage example or error handling interceptor next!
Your current approach—using an Axios request interceptor to automatically add the CSRF token to mutating requests—is solid and aligns well with best practices. To summarize and optimize your setup, here’s what I recommend:
1. Keep your Axios client with the interceptor
Add the CSRF token only to mutating HTTP methods: POST, PUT, PATCH, DELETE.
Use withCredentials: true to send cookies (including session and CSRF cookie).
early in app lifecycle (e.g., inside a root component’s useEffect) so the CSRF cookie is set and token cached before API calls.
3. Don’t manually pass CSRF token in every API call
Since the Axios interceptor handles token injection, API call code (like submitSignupStageZeroEmail) should focus on data only, making your code cleaner and less error-prone.
4. Confirm Backend CSRF & Cookies Setup
Yii2 backend must be configured to send CSRF token cookie with:
httpOnly: false (so frontend JS can read)
secure and sameSite set appropriately for your environment
Ensure session and CSRF cookie have distinct names and scopes
Backend validates CSRF token by matching header and cookie (or session token).
5. Optional: Improve CSRF Token Reading Logic
If you face token mismatch or timing issues:
Add a small delay before reading the cookie after token fetch
Log tokens to inspect differences
Consider trusting the backend token over the cookie if mismatch persists (at least during initial load)
6. Add error handling response interceptors
For improved UX and security, handle 419 (CSRF expired) or 401 (unauthorized) response globally and refresh tokens or redirect as needed.
7. XSS protection
Since your tokens are exposed in JS (due to httpOnly: false), ensure strong XSS protections via Content Security Policy and sanitization.
Final takeaway:
Your current approach with an Axios interceptor adding CSRF tokens from a singleton manager is excellent. Focus next on smooth initialization of the token, robust backend config, and centralized error handling. Avoid passing tokens explicitly per API call for simplicity and safety.
If you want, I can provide a minimal working example integrating all these recommendations end-to-end!
I understand your frustration — these CSRF + CORS setups can be quite tricky. Since you've already shared your code and logs, and you’re still hitting issues, let's do a precise diagnostic checklist and a focused fix to get your setup working.
Current Symptoms Recap
Your axios client throws Network Error when fetching CSRF token.
CSRF cookie content does not match backend token or contains serialized PHP session data.
You have correctly implemented axios interceptor and csrfTokenManager.
Backend logs show CSRF token generated properly.
Browser cookies show serialized session cookie under the CSRF token name or mismatch.
Frontend sometimes reads wrong cookie or token too early.
Step-by-step troubleshooting & fix plan
Step 1: Make sure backend cookies do not conflict
Add explicit different cookie names for session and CSRF in your Yii2 config:
// In your main config (web.php or similar)
'request' => [
'csrfParam' => '_csrf',
'csrfCookie' => [
'name' => 'csrfToken',
'httpOnly' => false,
'secure' => YII_ENV_PROD,
'sameSite' => YII_ENV_PROD ? \yii\web\Cookie::SAME_SITE_NONE : \yii\web\Cookie::SAME_SITE_LAX,
'path' => '/', // must be '/'
],
],
'session' => [
'name' => 'YIISESSID', // Use a distinct session cookie name, NOT "csrfToken"
'cookieParams' => [
'httpOnly' => true,
'secure' => YII_ENV_PROD,
'sameSite' => YII_ENV_PROD ? 'Strict' : 'Lax',
'path' => '/',
],
],
Clear all browser cookies for your backend domain manually before testing, to avoid stale/multiple cookies.
Step 2: Verify backend sets the CSRF cookie
Add logging in your CSRF token action:
public function actionCsrfToken()
{
$request = Yii::$app->request;
$token = $request->getCsrfToken();
Yii::info("CSRF token to send to client: $token", __METHOD__);
Yii::info('Sending CSRF cookie with params: ' . json_encode(Yii::$app->response->cookies->toArray()), __METHOD__);
// Let Yii handle cookie setting, no manual cookie add needed
return [
'csrfParam' => $request->csrfParam,
'csrfToken' => $token,
];
}
Step 3: Test backend API directly
Use curl or Postman to test /api/api-security/csrf-token endpoint:
Response contains Set-Cookie: csrfToken=... header with your token
Response body contains CSRF token JSON with matching token
No multiple Set-Cookie headers or weird cookie values
Step 4: Ensure frontend reads the correct cookie
In your csrfServices.ts:
export const CSRF_COOKIE_NAME = 'csrfToken';
export function getCsrfTokenFromCookie(): string | undefined {
console.log('Cookies seen by js-cookie:', Cookies.get());
return Cookies.get(CSRF_COOKIE_NAME);
}
Step 5: Delay token reading after fetching
Reading the cookie immediately after API response may be too soon. Add a delay:
export async function fetchCsrfToken(): Promise<CsrfData> {
const response = await apiClient.get(ENDPOINTS.security.csrfToken);
const { csrfParam, csrfToken } = response.data;
if (!csrfParam || !csrfToken) {
throw new Error('Failed to fetch CSRF token');
}
// wait 50-100ms to allow cookie to become available
await new Promise(r => setTimeout(r, 100));
const cookieToken = getCsrfTokenFromCookie();
if (!cookieToken) {
throw new Error('CSRF token cookie missing.');
}
if (cookieToken.trim() !== csrfToken.trim()) {
throw new Error(`CSRF tokens mismatch. Cookie: ${cookieToken}, Backend: ${csrfToken}`);
}
return { csrfParam, csrfToken };
}
Step 6: Check the Axios baseURL and network
Make sure your apiClient has correct baseURL:
const apiClient = axios.create({
baseURL: 'http://localhost:5000', // Make sure this is your backend URL with port
withCredentials: true,
headers: { 'Content-Type': 'application/json' },
timeout: 10000,
});
Check browser DevTools network tab:
Is the request going to the proper backend URL?
Is CORS preflight OPTIONS successful (HTTP 200)?
Are Set-Cookie headers present in response?
Step 7: Ensure CORS config permits your frontend origin