【问题标题】:How to retrieve laravel CSRF token using separated vue frontend如何使用分离的 vue 前端检索 laravel CSRF 令牌
【发布时间】:2020-11-21 19:30:14
【问题描述】:

鉴于 Laravel 后端和 Vue 前端彼此分离(在不同的目录和不同的子域中),有没有办法将 Laravel csrf 令牌传递给 Vue??

我正在构建一个应用程序,并希望将后端和前端分开,以用于组织目的,因为它有助于团队合作。所以,它会是这样的:

  • api.mydomainexample.com(Laravel 后端)
  • mydomainexample.com(面向公众的 Vue 前端)
  • admin.mydomainexample.com(Vue 前端仅适用于管理员)

这可能吗?我的想法可能是为前端项目运行 nodejs 服务器并使 nodejs 服务器与 laravel 服务器通信。不知道该怎么做。

我找到了similiar stackoverflow questions,但他们的回复并没有解决我的问题。我找到的最好的东西是this,它建议使用 Laravel 护照。但是,该提案是唯一有效的吗?如果是这样,Laravel 护照是否可以保护用户免受 CSRF 攻击?

实际上,如果有一种解决方法可以在保护 CSRF 令牌的同时分离后端和前端,那将是完美的!

【问题讨论】:

  • 你在哪里提供你的 vue 文件,来自 nodejs 服务器或 laravel 的 rotue?
  • 目前,我正在提供来自 Laravel 网络路由的 vue 文件。但我计划创建一个 nodejs 服务器来提供文件,因为目标是将后端与前端分开
  • 或者你可以使用 Laravel Sanctum 来处理你的前端认证;它对 SPA 的 csrf 功能做得很好,而且比护照轻。
  • 我们的工作场所也有类似的系统,我们使用 laravel 路由提供 vue 文件,使用 nodejs 和 socketio 仅用于实时通信。我实际上不能说完全独立的文件..

标签: laravel vue.js csrf


【解决方案1】:

使用Sanctum

LARAVEL 后端

  1. 通过 Composer 安装 Sanctum

    composer require laravel/sanctum


  1. 发布 Sanctum 配置和迁移文件

    php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"


  1. 运行您的迁移 - Sanctum 将添加一个表来存储 API 令牌

    php artisan migrate


  1. 将 Sanctum 的中间件添加到您的 App/Http/Kernel.php 中的 api 中间件组

use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

'api' => [
    EnsureFrontendRequestsAreStateful::class,
    'throttle:60,1',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
  1. 配置您的 SPA 将从哪些域发出请求。从文档:

您可以使用 sanctum 配置文件中的状态配置选项来配置这些域。此配置设置确定在向您的 API 发出请求时,哪些域将使用 Laravel 会话 cookie 维护“有状态”身份验证。

所以 - 更新您的 config\sanctum.php 以包含以下内容:

/*
    |--------------------------------------------------------------------------
    | Stateful Domains
    |--------------------------------------------------------------------------
    |
    | Requests from the following domains / hosts will receive stateful API
    | authentication cookies. Typically, these should include your local
    | and production domains which access your API via a frontend SPA.
    |
    */

    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,localhost:8000,127.0.0.1,127.0.0.1:8000,::1')),

  1. 配置您的config/cors.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', '*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

];
  1. 配置您的config/session.php

/*
    |--------------------------------------------------------------------------
    | Session Cookie Domain
    |--------------------------------------------------------------------------
    |
    | Here you may change the domain of the cookie used to identify a session
    | in your application. This will determine which domains the cookie is
    | available to in your application. A sensible default has been set.
    |
    */

    'domain' => env('SESSION_DOMAIN', null),
  1. 在您的.env 中,添加以下内容:

// Change .your-site.local to whatever domain you are using
// Please note the leading '.'

SESSION_DOMAIN=.your-site.local 
SANCTUM_STATEFUL_DOMAINS=your-site.local:8000
CORS_ALLOWED_ORIGINS=http://app.your-site.local:8000

  1. 运行php artisan config:clear

VUE 前端

  1. 在您的前端,创建以下文件夹/文件结构 @/src/services/api.js

api.js

import axios from 'axios';

const apiClient = axios.create({
    baseURL: process.env.VUE_APP_API_URL,
    withCredentials: true,
});

export default apiClient;

在根目录中,放置一个 .env 文件,其中包含以下内容:

VUE_APP_API_URL= 'http://api.your-site.local'  
  1. 要进行身份验证,您的 SPA 应首先向 /sanctum/csrf-cookie 发出请求。这将设置XSRF-TOKEN cookie。此令牌需要在后续请求中发送(axios 会自动为您处理)。紧接着,你需要向你的 Laravel /login 路由发送一个 POST 请求。
在您的 Vue 前端登录组件上:
import Vue from 'vue'
import apiClient from '../services/api';

export default {
  data() {
    return {
        email: null,
        password: null,
        loading: false,
    };
  },
  methods: {

    async login() {
      this.loading = true; // can use this to triggle a :disabled on login button
      this.errors = null;

        try {
          await apiClient.get('/sanctum/csrf-cookie'); 
          await apiClient.post('/login', {
            email: this.email,
            password: this.password
          });

          // Do something amazing
          
        } catch (error) {
          this.errors = error.response && error.response.data.errors;
        }

      this.loading = false;
    },

  },

【讨论】:

  • 非常感谢!我会在接下来的几天里试一试,让你知道它是否有效!
  • 完美!那太完美了!它就像一个魅力,很容易安装!非常感谢,真诚的
  • 我很高兴@StudentofScience!我刚刚经历了同样的事情,所以时机很好
猜你喜欢
  • 2021-04-06
  • 2020-11-22
  • 2017-02-17
  • 2020-10-29
  • 1970-01-01
  • 2018-10-23
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
相关资源
最近更新 更多