2025-05-23 18:51:19…
- User
2025-05-23 18:51:19 [::1][-][-][trace][app\controllers\ApiSecurityController::actionCsrfToken] CSRF Token from getCsrfToken(): RpddH38dvW6myQxuKQHP18KW1nadtYYhQLClywmDdIQF7nBIJ1ftA8zxRV1bOLWzrKKDF9X0y1Jz9_yAOOwlvA== 2025-05-23 18:51:19 [::1][-][-][info][app\controllers\ApiSecurityController::actionCsrfToken] CSRF token to send to client: RpddH38dvW6myQxuKQHP18KW1nadtYYhQLClywmDdIQF7nBIJ1ftA8zxRV1bOLWzrKKDF9X0y1Jz9_yAOOwlvA== 2025-05-23 18:51:19 [::1][-][-][info][app\controllers\ApiSecurityController::actionCsrfToken] Sending CSRF cookie with params: []
public function actionCsrfToken(): array { $request = \Yii::$app->request; if (!$request->isGet) { throw new BadRequestHttpException('Only GET requests are allowed.'); } $token = $request->getCsrfToken(); \Yii::debug('CSRF Token from getCsrfToken(): ' . $token, __METHOD__); /** * Explicitly add CSRF cookie to response (forces Set-Cookie header) * Note: No need to set cookie manually here */ $response = \Yii::$app->response; /*$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, 'path' => '/',// Ensure cookie always overrides previous cookies on all paths ]) );//*/ /** * Cookie check * foreach ($response->cookies as $cookie) { \Yii::info("Set-Cookie: {$cookie->name} = {$cookie->value}", __METHOD__); }//*/ \Yii::info("CSRF token to send to client: $token", __METHOD__); \Yii::info('Sending CSRF cookie with params: ' . json_encode($response->cookies->toArray()), __METHOD__); // 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, ]; }(2025-05-23T18:51:19.365Z) [All cookies via js-cookie:] {_csrf: 'cf311952abef22898e59561b0f730a118d4aae4d893228c819…rf";i:1;s:32:"Cy-WXJPmj8I3r9zdn4UaHAMs3GYK1oQ8";}'} _csrf : "cf311952abef22898e59561b0f730a118d4aae4d893228c8192edc58863ba9aea:2:{i:0;s:5:"_csrf";i:1;s:32:"Cy-WXJPmj8I3r9zdn4UaHAMs3GYK1oQ8";}" [[Prototype]] : Object loggerUtils.ts:235 (2025-05-23T18:51:19.365Z) [csrfServices.ts] Could not fetch CSRF token from backend Error: CSRF token cookie missing. at fetchCsrfToken (csrfServices.ts:62:9) at async csrfServices.ts:110:38 loggerUtils.ts:151 (2025-05-23T18:51:19.366Z) [All cookies via js-cookie:] {_csrf: 'cf311952abef22898e59561b0f730a118d4aae4d893228c819…rf";i:1;s:32:"Cy-WXJPmj8I3r9zdn4UaHAMs3GYK1oQ8";}'} _csrf : "cf311952abef22898e59561b0f730a118d4aae4d893228c8192edc58863ba9aea:2:{i:0;s:5:"_csrf";i:1;s:32:"Cy-WXJPmj8I3r9zdn4UaHAMs3GYK1oQ8";}" [[Prototype]] : Object
// src/services/csrfServices.ts import Cookies from 'js-cookie'; import apiClient from './apiClientServices'; import { ENDPOINTS } from '../constants/apiConstants'; import logger from '../utils/loggerUtils';
- Assistant
- User
- Assistant
- User
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'); } // Just trust backend token and do not validate with cookie logger.log('csrfServices.ts', 'Token from backend response:', csrfToken); return { csrfParam, csrfToken };}
can we add a more detailed comment why to just trust the token and not to validate between the two, so i dont forget
- Assistant
Certainly! Here's the updated function with a detailed explanatory comment about why you should trust the backend token and not compare it with the cookie value:
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'); } /** * IMPORTANT: * * The backend sends the CSRF token in the JSON response as a plain string. * * While the backend also sets a CSRF cookie (e.g., named 'csrfToken'), this cookie's value * is signed and serialized by the Yii framework to prevent tampering. * That means the cookie does NOT contain the raw token string but a protected value * including a signature and serialized data. * * Because of that, attempting to read the CSRF token directly from the cookie on the frontend * and compare it with the token from backend JSON response will fail due to mismatched formats. * * Therefore, it is best practice to trust the backend JSON token directly for sending in headers * and not attempt to read or validate the CSRF token from the cookie value. * * This approach avoids dealing with Yii's cookie signing mechanics on the client side, * simplifies the CSRF token management, * and ensures synchronization without false mismatches. */ logger.log('csrfServices.ts', 'Token from backend response:', csrfToken); return { csrfParam, csrfToken }; } - User
"if your client and server are same-origin, you can rely on X-CSRF-Token header with token from backend JSON response."
so how would I do this instead?
- Assistant
- User
- Assistant
- User
Your backend sets two cookies:
_csrf → the Yii default CSRF cookie (signed & serialized) csrfToken → your manually-set cookie with the token returned by your custom action (also signed & serialized by Yii)Your CSRF token API returns JSON with:
{ "csrfParam": "_csrf", "csrfToken": "theRawTokenString" }
this is why the tokens dont match?! I need to send:
$response->cookies->add( new Cookie([ //'name' => $request->csrfParam,// This would use '_csrf' 'name' => 'csrfToken', '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, 'path' => '/',// Ensure cookie always overrides previous cookies on all paths ]) );as also a json response
- Assistant
- User
"If you want, I can also help you adjust your frontend CSRF_COOKIE_NAME and csrfTokenManager accordingly. Would you like that?"
pl
- Assistant
- User
(2025-05-23T19:25:30.183Z) [All cookies via js-cookie:] 180dcb07c34b7d9c5698536f086ee456093d7c7341f3c297b2e38ae3a8798512a:2:{i:0;s:5:"_csrf";i:1;s:32:"ujvDJ4dNrznJwhn-ttJy3-KprBEKeuD2";} loggerUtils.ts:151 (2025-05-23T19:25:30.183Z) [csrfServices.ts] Token from backend response: YuQUBesZbOm6VZ9Qa1fe8GlZPFIhHZ-eaUKLEWcATkIXjmJBoS0Ip8gv8RocP7DdHS12KxIw1O4bAM5aAnUKcA== loggerUtils.ts:151 (2025-05-23T19:25:30.183Z) [csrfServices.ts] Token from cookie: 180dcb07c34b7d9c5698536f086ee456093d7c7341f3c297b2e38ae3a8798512a:2:{i:0;s:5:"_csrf";i:1;s:32:"ujvDJ4dNrznJwhn-ttJy3-KprBEKeuD2";} loggerUtils.ts:151 (2025-05-23T19:25:30.183Z) [All cookies via js-cookie:] 180dcb07c34b7d9c5698536f086ee456093d7c7341f3c297b2e38ae3a8798512a:2:{i:0;s:5:"_csrf";i:1;s:32:"ujvDJ4dNrznJwhn-ttJy3-KprBEKeuD2";}
so if the backend is different, then should I not be resetting the cookie somehow anytime we are getting a new csrf? reset in the frontend(remove the cookie) make the call(Get) to the backend and this should then make sure the front and back are the same
- Assistant
- User
so theirs no point in having a return from the backend, since it does not match or align with the cookie itself and im wasting my time
- Assistant
Not quite — the backend’s returning the raw CSRF token in JSON is actually important and useful, even if the cookie itself is signed and looks different.
- User
ok so i need both, is everything I have setup proper for this to work as it should?!
- Assistant
- User
Why you still want the backend to return the token in JSON (and how to use it)
You cannot reliably read the raw token from the signed cookie on the frontend. The cookie contains a signed and serialized value (security feature), so its value is not the plain token string. Your frontend needs the raw token string to send in request headers or request body parameters, to comply with Yii’s CSRF validation. The backend directly provides the raw token string in the JSON response, so your frontend can use it immediately to set the X-CSRF-Token header on API requests. Without this JSON token, your frontend would have no easy/secure way to get the token in a raw usable form.What the cookie vs JSON token distinction means for your app
The CSRF cookie enforces security by being signed (so clients cannot tamper) and sent automatically with requests. The token from backend JSON is a "secret" raw token that must be added to modifying requests (in headers or POST) as proof client and server sync. The backend verifies that the token sent in header or POST param matches the server token (which is linked to the cookie/session).can you make this into a comment for the backend that I can add at the return on why it needed
- Assistant
Certainly! Here's a clear, concise comment you can add in your backend code near the return statement explaining why the raw CSRF token is returned in JSON alongside the signed cookie:
/** * Return the raw CSRF token in JSON for frontend use. * * Note: * - The CSRF cookie sent to the client is signed and serialized by Yii for security, * so its value is NOT the raw token string and cannot be reliably read or used by JavaScript. * - The frontend needs the raw CSRF token string to include in request headers (e.g., 'X-CSRF-Token') * or POST parameters to comply with Yii's CSRF validation mechanism. * - Returning the raw token via JSON allows the frontend to securely obtain the usable token * without parsing or trusting the signed cookie. * - The signed cookie enforces token integrity and ties the token to the user's session, * while the raw token from JSON is the secret value the client must send back for validation. */ return [ 'csrfParam' => $request->csrfParam, 'csrfToken' => $token, ];This documents clearly why both mechanisms exist, and how the frontend and backend coordinate for secure CSRF protection.
- User
so anytime a form is set i need to get the token for hte return x-csrf-token?
- Assistant
Yes, exactly!
Summary
- Before submitting any form or making any state-changing request (POST, PUT, DELETE, etc.), your frontend needs to have the current valid raw CSRF token.
- User
wow i finally understand...
- Assistant
That’s awesome to hear — glad it clicked! 🎉
CSRF protection can definitely feel tricky because of the interplay between signed cookies and raw tokens, but once you see how the pieces fit, it becomes straightforward and secure.
If you have any more questions while implementing or want help with code examples, just ask. Happy coding! 🚀😊