React Fetch to Laravel API Creates New Session(React Fetch 到 Laravel API 创建新会话)
问题描述
My app is using React on the front end and Laravel 5.4 on the backend. I'm using fetch()
to request data from the backend. The problem is that two sessions are created when the page loads. A TokenMismatchException
is thrown by the CSRF Middleware when a POST
request is made because the token that is sent matches the first session that is created, but it checks against the second.
I'm setting the token in app.blade.php
<meta name="_token" content="{{ csrf_token() }}">
And grabbing the token in the fetch config
fetchConfig = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
credentials: 'same-origin'
}}
Here are the decrypted sessions:
a:3:{s:6:"_token";s:40:"7obvOzPaqqJDtVdij8RaqrvmTFLjKA2qnvYMxry6";s:9:"_previous";a:1:{s:3:"url";s:24:"http://localhost/page";}s:6:"_flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}
a:3:{s:6:"_token";s:40:"5Aiws9Qy72YzlkfWX81zkhzrSeiMDYjFWiLeDAwN";s:9:"_previous";a:1:{s:3:"url";s:41:"http://localhost/api/page";}s:6:"_flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}
Request URL: http://localhost/page
API URL: http://localhost/api/page
How can I prevent a new session from being created when the React app makes its initial GET
request?
Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application. : https://laravel.com/docs/5.4/csrf
APIs are stateless. There is nothing like session
in APIs. So you shouldn't use CSRF token in API. If you check Kernel.php
of laravel. You will see Tylor didn't add VerifyCsrf
middleware in API group. Which suggest that CSRF
is only used in the request having session i.e, stateful request. I would recommend you to use JWT based authentication system for API. For more about JWT check here.
You can use this laravel package for JWT : https://github.com/tymondesigns/jwt-auth
这篇关于React Fetch 到 Laravel API 创建新会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:React Fetch 到 Laravel API 创建新会话
基础教程推荐
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01