如何使用分离的vue前端检索Laravel CSRF令牌

时间:2020-08-01 00:09:08

标签: laravel vue.js csrf

考虑到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令牌的同时将后端和前端分开,那么那将是完美的!

1 个答案:

答案 0 :(得分:6)

使用Sanctum

LARAVEL BACKEND

  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 POST路由发送一个/login请求。
在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;
    },

  },