csrf token mismatch что это

Laravel Framework Russian Community

Пролог

Начало работы

Архитектурные концепции

Основное

Погружение

Безопасность

База данных

Eloquent ORM

Тестирование

Пакеты

Предотвращение атак CSRF

Введение

Межсайтовая подделка запроса – это разновидность вредоносного эксплойта, при котором неавторизованные команды выполняются от имени аутентифицированного пользователя. К счастью, Laravel позволяет легко защитить ваше приложение от Межсайтовой подделки запроса (Сross Site Request Forgery – CSRF).

Объяснение уязвимости

Без защиты от CSRF вредоносный веб-сайт может создать HTML-форму, которая указывает на маршрут вашего приложения /user/email и отправляет собственный адрес электронной почты злоумышленника:

Если вредоносный веб-сайт автоматически отправляет форму при загрузке страницы, злоумышленнику нужно только подтолкнуть ничего не подозревающего пользователя вашего приложения посетить свой веб-сайт, и его адрес электронной почты будет изменен в вашем приложении.

Предотвращение запросов от CSRF

Laravel автоматически генерирует «токен» CSRF для каждой активной пользовательской сессии, управляемой приложением. Этот токен используется для проверки того, что аутентифицированный пользователь действительно является лицом, выполняющим запросы к приложению. Поскольку этот токен хранится в сессии пользователя и изменяется каждый раз при повторном создании сессии, вредоносное приложение не может получить к нему доступ.

К CSRF-токену текущей сессии можно получить доступ через сессию запроса или с помощью глобального помощника csrf_token :

Каждый раз, когда вы создаете HTML-форму в своем приложении, вы должны включать в форму скрытое поле _token CSRF, чтобы посредник CSRF мог проверить запрос. Для удобства вы можете использовать директиву Blade @csrf для создания скрытого поля ввода, содержащего токен:

CSRF-токены и SPA-приложения

Если вы создаете SPA, который использует Laravel в качестве серверной части API, вам следует обратиться к документации Laravel Sanctum для получения информации об аутентификации с помощью вашего API и защите от уязвимостей CSRF.

Исключение URI из защиты от CSRF

По желанию можно исключить набор URI из защиты от CSRF. Например, если вы используете Stripe для обработки платежей и используете их систему веб-хуков, вам нужно будет исключить маршрут обработчика веб-хуков Stripe из защиты от CSRF, поскольку Stripe не будет знать, какой токен CSRF отправить вашим маршрутам.

Для удобства посредник CSRF автоматически отключается для всех маршрутов при выполнение тестов.

Токен X-CSRF

Затем, вы можете указать библиотеке, такой как jQuery, автоматически добавлять токен во все заголовки запросов. Это обеспечивает простую и удобную защиту от CSRF для ваших приложений с использованием устаревшей технологии JavaScript на основе AJAX:

Токен X-XSRF

Этот файл Cookies, в первую очередь, отправляется для удобства разработчика, поскольку некоторые фреймворки и библиотеки JavaScript, такие как Angular и Axios, автоматически помещают его значение в заголовок X-XSRF-TOKEN в запросах с одним и тем же источником.

Источник

Laravel csrf token mismatch for ajax POST Request

I am trying to delete data from database via ajax.

HTML:

My ajax code:

This is my query to fetch data from database.

But when i click on Delete link data not deleted and show csrf_token mismatch.

21 Answers 21

The best way to solve this problem «X-CSRF-TOKEN» is to add the following code to your main layout, and continue making your ajax calls normally:

In header

In script

You have to add data in your ajax request. I hope so it will be work.

I just added headers: in ajax call:

I think is better put the token in the form, and get this token by id

this way, your JS don’t need to be in your blade files.

If you are using template files, than you can put your meta tag in the head section (or whatever you name it) which contain your meta tags.

Next thing, you need to put the headers attribute to your ajax (in my example, I am using datatable with server-side processing:

Here is the full datatable ajax example:

After doing this, you should get 200 status for your ajax request.

Add an id to the meta element that holds the token

And then you can get it in your Javascript

EDIT: Easier way without changing the meta line.

Thanks to @martin-hartmann

Know that there is an X-XSRF-TOKEN cookie that is set for convenience. Framework like Angular and others set it by default. Check this in the doc https://laravel.com/docs/5.7/csrf#csrf-x-xsrf-token You may like to use it.

The best way is to use the meta, case the cookies are deactivated.

Читайте также:  что делать если божья коровка залетела в дом

Here the recommended meta way (you can put the field any way, but meta is quiet nice):

Here the section about the csrf cookie in the doc to check : https://laravel.com/docs/5.7/csrf#csrf-x-csrf-token

Also here how laravel (bootstrap.js) is setting it for axios by default:

And here read cookie function:

if you are using jQuery to send AJAX Posts, add this code to all views:

Laravel adds a XSRF cookie to all requests, and we automatically append it to all AJAX requests just before submit.

You may replace getCookie function if there is another function or jQuery plugin to do the same thing.

who ever is getting problem with the accepted answer @Deepak saini, try to remove

In case your session expires, you can use this, to login again

you have to include this line in master file

For Laravel 5.8, setting the csrf meta tag for your layout and setting the request header for csrf in ajax settings won’t work if you are using ajax to submit a form that already includes a _token input field generated by the Laravel blade templating engine.

You must include the already generated csrf token from the form with your ajax request because the server would be expecting it and not the one in your meta tag.

For instance, this is how the _token input field generated by Blade looks like:

You then submit your form with ajax like this:

The csrf token in the meta header is only useful when you are submitting a form without a Blade generated _token input field.

Источник

ERROR CSRF token mismatch #2719

Comments

StormYudi commented Nov 16, 2020 •

Background:

Describe
I’ve installed the latest 1.1.1 version panel in my CentOS 7 server, after the setup, I was trying to login in the panel, and then I’ve got an error with message CSRF token mismatch, http code 419.

The login form with X-CSRF-Token header is empty, I think something is wrong, is that a bug?

The text was updated successfully, but these errors were encountered:

DomiiBunn commented Nov 16, 2020

Most likley your php version is out of date. Try asking for help here 1st https://discord.gg/PN6eYsBY if that’s the solution close the issue please ^.^

StormYudi commented Nov 17, 2020

Most likley your php version is out of date. Try asking for help here 1st https://discord.gg/PN6eYsBY if that’s the solution close the issue please ^.^

Thanks for your help, But I am using PHP7.4 with Mysql 5.7 🙁

DomiiBunn commented Nov 17, 2020

StormYudi commented Nov 17, 2020

There is no logs 🙁 the file is empty, I will try to reinstall the panel in ubuntu, thanks

DomiiBunn commented Nov 17, 2020

There has to be a log if you get an error ^.^ try to go to the panel again and than run the log command

StormYudi commented Nov 17, 2020

I checked it again and it was really not there 🙁

mistermodcreator commented Nov 17, 2020 •

I got the same Error and the log is the following:

Probably this can help?

YajTPG commented Nov 18, 2020

Usually clearing Cookies fixes that error. (Atleast for me)

alexevladgabriel commented Nov 18, 2020

Are you using a ssl configuration with http:// connection?
Do you have generated ssl for that domain?

StormYudi commented Nov 20, 2020

@alexevladgabriel I am not using https at that time.

I simply reinstall the OS and reinstall the panel again, it works now, thank you all.

ajarmoszuk commented Dec 15, 2020

This is unfortunately still an issue, running PHP 7.4.13. Not sure what is happening but there is no information to suggest any issues. Nothing is to be found in the logs.

ajarmoszuk commented Dec 15, 2020

Site is running on HTTPS.

Techwolf12 commented Dec 23, 2020

No SSL here. It fails on creating a cookie «XSRF-TOKEN» because it wants to set it as secure and non-https cookies can’t be set as secure.

fabm3n commented Jan 12, 2021

No SSL here. It fails on creating a cookie «XSRF-TOKEN» because it wants to set it as secure and non-https cookies can’t be set as secure.

This would not change anything because the default value is already false: https://github.com/pterodactyl/panel/blob/develop/config/session.php#L163

Читайте также:  что делать если зуб гниет и болит

Dungeonseeker commented Feb 2, 2021

Same issue here on Ubuntu Server 20.10 running Apache & PHP 7.14

#0 /var/www/pterodactyl/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(358): Swift_Transport_AbstractSmtpTransport->assertResponseCode #1 /var/www/pterodactyl/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(147): Swift_Transport_AbstractSmtpTransport->readGreeting #2 /var/www/pterodactyl/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php(50): Swift_Transport_AbstractSmtpTransport->start #3 /var/www/pterodactyl/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer.php(65): Swift_Transport_SendmailTransport->start #4 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Mail/Mailer.php(521): Swift_Mailer->send #5 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Mail/Mailer.php(288): Illuminate\Mail\Mailer->sendSwiftMessage #6 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(65): Illuminate\Mail\Mailer->send #7 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(146): Illuminate\Notifications\Channels\MailChannel->send #8 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(105): Illuminate\Notifications\NotificationSender->sendToNotifiable #9 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Support/Traits/Localizable.php(19): Illuminate\Notifications\NotificationSender->Illuminate\Notifications\ #10 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(107): Illuminate\Notifications\NotificationSender->withLocale #11 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Notifications/ChannelManager.php(54): Illuminate\Notifications\NotificationSender->sendNow #12 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Notifications/SendQueuedNotifications.php(94): Illuminate\Notifications\ChannelManager->sendNow #13 (0): Illuminate\Notifications\SendQueuedNotifications->handle #14 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(33): call_user_func_array #15 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/Util.php(37): Illuminate\Container\BoundMethod::Illuminate\Container\ #16 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(91): Illuminate\Container\Util::unwrapIfClosure #17 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(35): Illuminate\Container\BoundMethod::callBoundMethod #18 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/Container.php(592): Illuminate\Container\BoundMethod::call #19 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(94): Illuminate\Container\Container->call #20 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Bus\Dispatcher->Illuminate\Bus\ #21 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\ #22 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(98): Illuminate\Pipeline\Pipeline->then #23 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(83): Illuminate\Bus\Dispatcher->dispatchNow #24 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Queue\CallQueuedHandler->Illuminate\Queue\ #25 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\ #26 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(85): Illuminate\Pipeline\Pipeline->then #27 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(59): Illuminate\Queue\CallQueuedHandler->dispatchThroughMiddleware #28 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(98): Illuminate\Queue\CallQueuedHandler->call #29 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(356): Illuminate\Queue\Jobs\Job->fire #30 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(306): Illuminate\Queue\Worker->process #31 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(132): Illuminate\Queue\Worker->runJob #32 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(112): Illuminate\Queue\Worker->daemon #33 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(96): Illuminate\Queue\Console\WorkCommand->runWorker #34 (0): Illuminate\Queue\Console\WorkCommand->handle #35 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(33): call_user_func_array #36 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/Util.php(37): Illuminate\Container\BoundMethod::Illuminate\Container\ #37 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(91): Illuminate\Container\Util::unwrapIfClosure #38 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(35): Illuminate\Container\BoundMethod::callBoundMethod #39 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/Container.php(592): Illuminate\Container\BoundMethod::call #40 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Console/Command.php(134): Illuminate\Container\Container->call #41 /var/www/pterodactyl/vendor/symfony/console/Command/Command.php(258): Illuminate\Console\Command->execute #42 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Console/Command.php(121): Symfony\Component\Console\Command\Command->run #43 /var/www/pterodactyl/vendor/symfony/console/Application.php(911): Illuminate\Console\Command->run #44 /var/www/pterodactyl/vendor/symfony/console/Application.php(264): Symfony\Component\Console\Application->doRunCommand #45 /var/www/pterodactyl/vendor/symfony/console/Application.php(140): Symfony\Component\Console\Application->doRun #46 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Console/Application.php(93): Symfony\Component\Console\Application->run #47 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(129): Illuminate\Console\Application->run #48 /var/www/pterodactyl/artisan(37): Illuminate\Foundation\Console\Kernel->handle [2021-02-02 19:43:10] production.ERROR: Swift_TransportException: Expected response code 220 but got an empty response in /var/www/pterodactyl/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:445 Stack trace: #0 /var/www/pterodactyl/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(358): Swift_Transport_AbstractSmtpTransport->assertResponseCode #1 /var/www/pterodactyl/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php(147): Swift_Transport_AbstractSmtpTransport->readGreeting #2 /var/www/pterodactyl/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/SendmailTransport.php(50): Swift_Transport_AbstractSmtpTransport->start #3 /var/www/pterodactyl/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mailer.php(65): Swift_Transport_SendmailTransport->start #4 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Mail/Mailer.php(521): Swift_Mailer->send #5 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Mail/Mailer.php(288): Illuminate\Mail\Mailer->sendSwiftMessage #6 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Notifications/Channels/MailChannel.php(65): Illuminate\Mail\Mailer->send #7 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(146): Illuminate\Notifications\Channels\MailChannel->send #8 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(105): Illuminate\Notifications\NotificationSender->sendToNotifiable #9 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Support/Traits/Localizable.php(19): Illuminate\Notifications\NotificationSender->Illuminate\Notifications\ #10 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Notifications/NotificationSender.php(107): Illuminate\Notifications\NotificationSender->withLocale #11 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Notifications/ChannelManager.php(54): Illuminate\Notifications\NotificationSender->sendNow #12 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Notifications/SendQueuedNotifications.php(94): Illuminate\Notifications\ChannelManager->sendNow #13 (0): Illuminate\Notifications\SendQueuedNotifications->handle #14 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(33): call_user_func_array #15 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/Util.php(37): Illuminate\Container\BoundMethod::Illuminate\Container\ #16 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(91): Illuminate\Container\Util::unwrapIfClosure #17 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(35): Illuminate\Container\BoundMethod::callBoundMethod #18 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/Container.php(592): Illuminate\Container\BoundMethod::call #19 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(94): Illuminate\Container\Container->call #20 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Bus\Dispatcher->Illuminate\Bus\ #21 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\ #22 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(98): Illuminate\Pipeline\Pipeline->then #23 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(83): Illuminate\Bus\Dispatcher->dispatchNow #24 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\Queue\CallQueuedHandler->Illuminate\Queue\ #25 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\ #26 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(85): Illuminate\Pipeline\Pipeline->then #27 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(59): Illuminate\Queue\CallQueuedHandler->dispatchThroughMiddleware #28 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(98): Illuminate\Queue\CallQueuedHandler->call #29 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(356): Illuminate\Queue\Jobs\Job->fire #30 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(306): Illuminate\Queue\Worker->process #31 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(132): Illuminate\Queue\Worker->runJob #32 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(112): Illuminate\Queue\Worker->daemon #33 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(96): Illuminate\Queue\Console\WorkCommand->runWorker #34 (0): Illuminate\Queue\Console\WorkCommand->handle #35 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(33): call_user_func_array #36 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/Util.php(37): Illuminate\Container\BoundMethod::Illuminate\Container\ #37 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(91): Illuminate\Container\Util::unwrapIfClosure #38 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(35): Illuminate\Container\BoundMethod::callBoundMethod #39 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Container/Container.php(592): Illuminate\Container\BoundMethod::call #40 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Console/Command.php(134): Illuminate\Container\Container->call #41 /var/www/pterodactyl/vendor/symfony/console/Command/Command.php(258): Illuminate\Console\Command->execute #42 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Console/Command.php(121): Symfony\Component\Console\Command\Command->run #43 /var/www/pterodactyl/vendor/symfony/console/Application.php(911): Illuminate\Console\Command->run #44 /var/www/pterodactyl/vendor/symfony/console/Application.php(264): Symfony\Component\Console\Application->doRunCommand #45 /var/www/pterodactyl/vendor/symfony/console/Application.php(140): Symfony\Component\Console\Application->doRun #46 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Console/Application.php(93): Symfony\Component\Console\Application->run #47 /var/www/pterodactyl/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(129): Illuminate\Console\Application->run #48 /var/www/pterodactyl/artisan(37): Illuminate\Foundation\Console\Kernel->handle

eupedroosouza commented Sep 19, 2021

Sem SSL aqui. Ele falha ao criar um cookie «XSRF-TOKEN» porque deseja definir como seguro e os cookies não https não podem ser definidos como seguros.
Consertar isso:

This worked for me, thanks!

SovernT13 commented Nov 21, 2021

No SSL here. It fails on creating a cookie «XSRF-TOKEN» because it wants to set it as secure and non-https cookies can’t be set as secure.

This also worked for me. I was using a custom installer script though.

jordi2010 commented Nov 21, 2021 •

No SSL here. It fails on creating a cookie «XSRF-TOKEN» because it wants to set it as secure and non-https cookies can’t be set as secure.

Worked for me. I used https first instead of http.
This setting was not changed back when going through the installer

Software-Noob commented Nov 21, 2021

We don’t offer any installers. If you have an issue with such, contact the author of it directly. The fix is above should someone stumble upon this in the future.

The value depends on what protocol scheme you choose during installation, and also, our support bot in Discord can respond to this issue.

Источник

CSRF token mismatch and Unauthenticated #41

Comments

mbougarne commented Jan 13, 2020

I can’t get it to work with Nuxt in the front-end, firstly I got the **419 ** error number when I tried to access to /login which is a CSRF token issue, I disabled the **CSRF ** token by adding wildcard access in VerifyCsrfToken Middleware:

I passed the login part with that, but I faced another one which is 401

Unauthenticated: Although I’m in the stateful mode

Laravel app is running on: http://localhost:8000/
Nuxt app is running on: http://localhost:3000/

I think, there’s an issue on «`EnsureFrontendRequestsAreStateful«
My Request using Axios as Nuxt Module:

The text was updated successfully, but these errors were encountered:

Читайте также:  lst питон что это

danpastori commented Jan 13, 2020

mbougarne commented Jan 14, 2020

driesvints commented Jan 14, 2020

I’ll leave this to @taylorotwell to investigate.

taylorotwell commented Jan 14, 2020

No. Airlock does not require you to put everything in the same app. I’ve tested it fine with Vue CLI. These are all CORS issues.

mbougarne commented Jan 14, 2020

I don’t think so, I used laravel-cors

monsterdream commented Jan 16, 2020

@mbougarne agree, that same situation here.

danpastori commented Jan 17, 2020

I got to this point yesterday and part of it was CORS. However if you are to the point where you are getting a valid 401 response, try changing the SESSION_DRIVER to cookie (mentioned in #11). A combination of correct CORS, SESSION_DOMAIN, and SESSION_DRIVER got this resolved.

I managed to get this working with the NuxtJS auth module as well and pushed the code to help out.

I wrote a quick guide to getting them working together focused mainly on NuxtJS frontend with their first class auth module: https://serversideup.net/using-laravel-airlock-with-nuxtjs/.

If you guys need any help, let me know!

SeinopSys commented Jan 18, 2020 •

I found that I needed the following middleware to get any form of working CSRF with the current instructions as written.

Reading the token from the cookie header like the middleware above does will not protect against CSRF since that cookie is sent along with the request regardless of where it came from, defeating the purpose of CSRF protection entirely.

billisonline commented Jan 24, 2020

@SeinopSys your solution worked for me, thanks!

SeinopSys commented Jan 24, 2020 •

@billisonline I sincerely hope that you meant appending the header via JS, otherwise, by adding that middleware in your codebase, you are effectively making CSRF protection pointless. I’ve edited my previous comment to make this clearer nonetheless.

wannymiarelli commented Feb 1, 2020 •

@SeinopSys Yes, this is what I actually did with fetch. The Laravel doc is clear about how to send back the CSRF token but yes, I think that would be a good idea to add some kind of reference in the readme.

steks89 commented Mar 6, 2020 •

@danpastori solution’s worked for me
SESSION_DRIVER=cookie (maybe is obvious for some people, but I think it could be in the airlock’s documentation),
Also people need to clear cookies before every test.

ouhaohan8023 commented Mar 13, 2020

I find another reason. If you use Api Token rather than SPA. Your app/Http/Kernel.php file should look like this

paprotsky commented Mar 19, 2020

tnduc commented Mar 20, 2020 •

@taylorotwell Can you support me

POST: /api/curent-user: message: «Unauthenticated.»

My config:
SESSION_DRIVER=cookie



patrikengborg commented Mar 23, 2020

I had this problem with getting an «Unauthenticated» error (401) for subsequent requests after a successful login. In my case it was because I made some API requests in nuxtServerInit or in the created hook. Because of how Nuxt works, those requests are made from the server and not from the client. And I guess the appropriate headers is not included then by default. I found two different solutions.

Make sure the request is made only from the client by using:

The other solution is to set proxyHeaders: true in the axios options. According to the docs:

In SSR context, this options sets client requests headers as default headers for the axios requests. This is useful for making requests which need cookie based auth on server side. This also helps making consistent requests in both SSR and Client Side code.

I hope this helps someone. I was banging my head for a while, before I figured out what was going on.

@taylorotwell @driesvints I think you would spare yourself a lot of support requests if you added a note about this trap in the docs. Many users seem to be stuck because of this, and think this is a problem with Sanctum, which it’s not. Nuxt and Laravel seems to be a popular combo, and it would be a shame if they gave up on using Sanctum because of this.

Источник

Сказочный портал