对Laravel API的React Fetch创建新会话 [英] React Fetch to Laravel API Creates New Session

查看:78
本文介绍了对Laravel API的React Fetch创建新会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序在前端使用React,在后端使用Laravel 5.4.我正在使用fetch()从后端请求数据.问题是页面加载时会创建两个会话.发出POST请求时,CSRF中间件将引发TokenMismatchException,因为发送的令牌与创建的第一个会话匹配,但会与第二个会话进行对照.

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.

我正在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'
}}

这是解密的会话:

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:{}}}

请求网址:http://localhost/page

API URL:http://localhost/api/page

当React应用发出其初始GET请求时,如何防止创建新会话?

How can I prevent a new session from being created when the React app makes its initial GET request?

推荐答案

Laravel为应用程序管理的每个活动用户会话自动生成CSRF令牌".此令牌用于验证经过身份验证的用户是实际向应用程序发出请求的用户. : https://laravel.com/docs/5.4/csrf

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

API是无状态的. API中没有类似session的东西.因此,您不应在API中使用CSRF令牌.如果您查看laravel的 Kernel.php .您将看到Tylor没有在API组中添加VerifyCsrf中间件.这表明CSRF仅用于具有会话的请求,即有状态请求.我建议您对API使用基于JWT的身份验证系统.有关JWT的更多信息,在此处检查.

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.

您可以将此laravel软件包用于JWT: https://github.com/tymondesigns/jwt-auth

You can use this laravel package for JWT : https://github.com/tymondesigns/jwt-auth

这篇关于对Laravel API的React Fetch创建新会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆