Reputation: 3567
I have one server running Yii2 with only API endpoints, and one server with a single-page application that fetches all data from the Yii server.
I'm storing a JWT-Token in a cookie on successful login by the application, and I have a custom AuthMethod based on this.
My issue is CSRF Protection that have to be in place when cookies are used for authentication. The yii application automatically sets a _csrf
cookie, but it does not do much at the moment.
As far as I can understand, I need to provide this csrf token to the frontend application on login, so that it can be stored in local storage and send in the headers for all subsequent requests.
I've implemented a check for the csrf token using Yii::$app->request->csrfTokenFromHeader
and sending the token in X-CSRF-Token
http header.
I'm unable to extract the same value as the one stored in the cookie inside the application. Yii::$app->request->getCsrfToken()
and Yii::$app->request->csrfToken
both return a different token than the one stored in the _csrf
-cookie.
This is from my login endpoint:
$token = $model->setCookie(); // Sets the JWT-Token HttpOnly Cookie
$response = [
'message' => 'Login successful',
'csrf-token' => Yii::$app->request->getCsrfToken() // This does not match the _csrf cookie
];
Upvotes: 1
Views: 2497
Reputation: 3567
After reading some more in the source code, I discovered that the token needs to be unmasked. This is done in Request->validateCsrfTokenInternal()
that are called with Request->validateCsrfToken()
.
I added the following line to my AuthMethod:
if (!\Yii::$app->request->validateCsrfToken()) throw new HttpException(401, 'Invalid CSRF Token');
And that automatically checks the X-CSRF-Token
-header.
I'm leaving the question in case anyone else have the same problem.
Upvotes: 2