adic3x's avatar

CSRF token random mismatch

Hello to all.

I develop SPA app with Laravel. This app periodically send some 'get_updates' requests to server to get actual info. In 5% cases this request fails with 419 or 500 error code. It works on my local machine with XAMPP. I did not seem to change any configuration files or middleware that could affect the processing of this token.

In *.blade I get CSRF token:

const CSRF_VALUE = '{{ csrf_token() }}';

My ajax request:

$.ajax({
    url: ROUTE_GET_ATHLETE_LIST,
    type: 'POST',
    dataType: 'json',
    data: `_token=${CSRF_VALUE}`,
})

It works fine in 95% cases. But if I don't close tab in browser within a few hours I got these errors:

imgur[dot]com/a/uPaBrPb

Requests are identically.

419 response:

{message: "CSRF token mismatch.", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…}
exception: "Symfony\Component\HttpKernel\Exception\HttpException"
file: "C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php"
line: 396
message: "CSRF token mismatch."
trace: [{,…},…]

500 response:

{,…}
exception: "Illuminate\Database\QueryException"
file: "C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Database\Connection.php"
line: 760
message: "SQLSTATE[HY000] [1045] Access denied for user 'forge'@'localhost' (using password: NO) (SQL: select * from `users` where `id` = 1 limit 1)"
trace: [,…]

200 and 500 has XSRF-TOKEN in pesponse, but not 419.

Only ideas I found on the internet are:

php artisan config:cache
or
php artisan cache:clear 

I don't tried this. I have a hard to reproduce bug, so for now I don't want to change anything to be able to get more information about it.

If you need any more information to clarify, please let me know.

I will be grateful for any hints.

0 likes
12 replies
vincent15000's avatar

Why don't you send the CSRF token automatically via the standard Laravel configuration ?

adic3x's avatar

@vincent15000 By standard configuration you mean as this:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

?

Another way to pass the token could affect my issue?

1 like
adic3x's avatar

@vincent15000 jQuery. But what does it matter? If you think that such random errors are caused by an incorrect request - just tell me what can be changed in it.

1 like
vincent15000's avatar

@adic3x I don't understand why you need jQuery to send request in a pure Laravel project.

Can you give an example of your code ?

Snapey's avatar

after 2 hours the session will expire and the next request will start a new session and generate a new csrf token.

You could avoid this by having a simple function that runs very 30 minutes using setTimeout (for example) and does a simple fetch on one of the app's routes. This will keep the session alive.

2 likes
adic3x's avatar

@Snapey

If I understand correctly, new CSRF token will be generated at the start of a new session.

App receives a token on boot, makes N successful requests, then N + 1 request fails, but then N + 2 request succeeds (with same token) a minute after N + 1.

You can see it in the screenshots on imgur.

Requests are made every minute (apparently Chrome "freezes" the tabs in the background).

1 like
Snapey's avatar

What is the 500 error? Look in your logs.

1 like
adic3x's avatar

@Snapey it's SQL error 'SQLSTATE[HY000] [1045] Access denied for user 'forge'@'localhost' (using password: NO)'. I'm not sure if these two errors (419 and 500) have same origin.

Also, in .env I use:

SESSION_DRIVER=file
SESSION_LIFETIME=120

My routes which fails use ['auth', 'verified'] middleware.

Full error log 419, there is only vendors code:

[2023-05-28 18:57:20] production.ERROR: No application encryption key has been specified. {"exception":"[object] (Illuminate\Encryption\MissingAppKeyException(code: 0): No application encryption key has been specified. at C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Encryption\EncryptionServiceProvider.php:79)
[stacktrace]
#0 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Support\helpers.php(306): Illuminate\Encryption\EncryptionServiceProvider->Illuminate\Encryption\{closure}(NULL)
#1 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Encryption\EncryptionServiceProvider.php(77): tap(NULL, Object(Closure))
#2 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Encryption\EncryptionServiceProvider.php(60): Illuminate\Encryption\EncryptionServiceProvider->key(Array)
#3 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Encryption\EncryptionServiceProvider.php(32): Illuminate\Encryption\EncryptionServiceProvider->parseKey(Array)
#4 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Container\Container.php(871): Illuminate\Encryption\EncryptionServiceProvider->Illuminate\Encryption\{closure}(Object(Illuminate\Foundation\Application), Array)
#5 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Container\Container.php(756): Illuminate\Container\Container->build(Object(Closure))
#6 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(860): Illuminate\Container\Container->resolve('encrypter', Array, true)
#7 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Container\Container.php(692): Illuminate\Foundation\Application->resolve('encrypter', Array)
#8 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(845): Illuminate\Container\Container->make('encrypter', Array)
#9 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Container\Container.php(1029): Illuminate\Foundation\Application->make('encrypter')
#10 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Container\Container.php(945): Illuminate\Container\Container->resolveClass(Object(ReflectionParameter))
#11 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Container\Container.php(906): Illuminate\Container\Container->resolveDependencies(Array)
#12 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Container\Container.php(756): Illuminate\Container\Container->build('App\\Http\\Middle...')
#13 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(860): Illuminate\Container\Container->resolve('App\\Http\\Middle...', Array, true)
#14 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Container\Container.php(692): Illuminate\Foundation\Application->resolve('App\\Http\\Middle...', Array)
#15 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(845): Illuminate\Container\Container->make('App\\Http\\Middle...', Array)
#16 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(239): Illuminate\Foundation\Application->make('App\\Http\\Middle...')
#17 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(203): Illuminate\Foundation\Http\Kernel->terminateMiddleware(Object(Illuminate\Http\Request), Object(Illuminate\Http\JsonResponse))
#18 C:\xampp\htdocs\phpl\Sport\public\index.php(56): Illuminate\Foundation\Http\Kernel->terminate(Object(Illuminate\Http\Request), Object(Illuminate\Http\JsonResponse))
#19 {main}
"} 

500:

[2023-05-28 19:22:20] local.ERROR: SQLSTATE[HY000] [1045] Access denied for user 'forge'@'localhost' (using password: NO) (SQL: select * from `users` where `id` = 1 limit 1) {"exception":"[object] (Illuminate\Database\QueryException(code: 1045): SQLSTATE[HY000] [1045] Access denied for user 'forge'@'localhost' (using password: NO) (SQL: select * from `users` where `id` = 1 limit 1) at C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Database\Connection.php:760)
[stacktrace]
#0 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Database\Connection.php(720): Illuminate\Database\Connection->runQueryCallback('select * from `...', Array, Object(Closure))
#1 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Database\Connection.php(405): Illuminate\Database\Connection->run('select * from `...', Array, Object(Closure))
#2 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php(2653): Illuminate\Database\Connection->select('select * from `...', Array, true)
#3 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php(2642): Illuminate\Database\Query\Builder->runSelect()
#4 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php(3178): Illuminate\Database\Query\Builder->Illuminate\Database\Query\{closure}()
#5 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php(2641): Illuminate\Database\Query\Builder->onceWithColumns(Array, Object(Closure))
#6 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Builder.php(710): Illuminate\Database\Query\Builder->get(Array)
#7 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Builder.php(694): Illuminate\Database\Eloquent\Builder->getModels(Array)
#8 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Database\Concerns\BuildsQueries.php(296): Illuminate\Database\Eloquent\Builder->get(Array)
#9 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Auth\EloquentUserProvider.php(59): Illuminate\Database\Eloquent\Builder->first()
#10 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Auth\SessionGuard.php(159): Illuminate\Auth\EloquentUserProvider->retrieveById(1)
#11 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Auth\GuardHelpers.php(60): Illuminate\Auth\SessionGuard->user()
#12 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php(63): Illuminate\Auth\SessionGuard->check()
#13 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php(42): Illuminate\Auth\Middleware\Authenticate->authenticate(Object(Illuminate\Http\Request), Array)
#14 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Auth\Middleware\Authenticate->handle(Object(Illuminate\Http\Request), Object(Closure))
#15 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Routing\Middleware\SubstituteBindings.php(50): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#16 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Routing\Middleware\SubstituteBindings->handle(Object(Illuminate\Http\Request), Object(Closure))
#17 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php(78): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#18 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure))
#19 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\View\Middleware\ShareErrorsFromSession.php(49): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#20 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\View\Middleware\ShareErrorsFromSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#21 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Session\Middleware\StartSession.php(121): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#22 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Session\Middleware\StartSession.php(64): Illuminate\Session\Middleware\StartSession->handleStatefulRequest(Object(Illuminate\Http\Request), Object(Illuminate\Session\Store), Object(Closure))
#23 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Session\Middleware\StartSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#24 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse.php(37): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#25 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle(Object(Illuminate\Http\Request), Object(Closure))
#26 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\EncryptCookies.php(67): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#27 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Cookie\Middleware\EncryptCookies->handle(Object(Illuminate\Http\Request), Object(Closure))
#28 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(116): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#29 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Routing\Router.php(797): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#30 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Routing\Router.php(776): Illuminate\Routing\Router->runRouteWithinStack(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
#31 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Routing\Router.php(740): Illuminate\Routing\Router->runRoute(Object(Illuminate\Http\Request), Object(Illuminate\Routing\Route))
#32 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Routing\Router.php(729): Illuminate\Routing\Router->dispatchToRoute(Object(Illuminate\Http\Request))
#33 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(190): Illuminate\Routing\Router->dispatch(Object(Illuminate\Http\Request))
#34 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(141): Illuminate\Foundation\Http\Kernel->Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))
#35 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#36 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull.php(31): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
#37 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull->handle(Object(Illuminate\Http\Request), Object(Closure))
#38 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php(21): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#39 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TrimStrings.php(40): Illuminate\Foundation\Http\Middleware\TransformsRequest->handle(Object(Illuminate\Http\Request), Object(Closure))
#40 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Foundation\Http\Middleware\TrimStrings->handle(Object(Illuminate\Http\Request), Object(Closure))
#41 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ValidatePostSize.php(27): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#42 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Foundation\Http\Middleware\ValidatePostSize->handle(Object(Illuminate\Http\Request), Object(Closure))
#43 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance.php(86): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#44 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance->handle(Object(Illuminate\Http\Request), Object(Closure))
#45 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Http\Middleware\HandleCors.php(62): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#46 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Http\Middleware\HandleCors->handle(Object(Illuminate\Http\Request), Object(Closure))
#47 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Http\Middleware\TrustProxies.php(39): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#48 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Http\Middleware\TrustProxies->handle(Object(Illuminate\Http\Request), Object(Closure))
#49 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(116): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#50 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(165): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#51 C:\xampp\htdocs\phpl\Sport\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(134): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
#52 C:\xampp\htdocs\phpl\Sport\public\index.php(52): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#53 {main}
adic3x's avatar
adic3x
OP
Best Answer
Level 1

Okay. it's looks like I fix it:

php artisan cache:clear
php artisan config:clear
php artisan route:clear

php artisan config:cache
php artisan route:cache
php artisan optimize

I don't know which command fix cache, but now it's works fine.

The trouble is incorrect reading from .env file; 'forge' - default username for DB access. When reading actual username/password from .env failing - Laravel use this name. And crashes with this wrong value.

config\database.php:

        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),

In case with CSRF - I think Laravel can't read APP_KEY value. Or maybe fail with SESSION_DRIVER and then Laravel can't get user session data. Anyway CSRF validation fails.

1 like

Please or to participate in this conversation.