如何使用分离的vue前端检索Laravel CSRF令牌 [英] How to retrieve laravel CSRF token using separated vue frontend

查看:79
本文介绍了如何使用分离的vue前端检索Laravel CSRF令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to pass Laravel csrf token to Vue given that the Laravel backend and the Vue frontend are separated from each other (in diferent directory and in diferent subdomains) ??

我正在构建一个应用程序,并希望将后端和前端分开用于组织目的,因为它可以促进团队合作。因此,就像这样:

I'm building an application and would like to have separated backend and frontend for organization purposes and for because it facilitates team work. So, it would be something like:


  • api.mydomainexample.com(Laravel后端)

  • mydomainexample.com( Vue前端公共)

  • admin.mydomainexample.com(仅Vue前端用于管理员)

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

Is this possible? What I thought was maybe running a nodejs server for the frontend project and make the nodejs server communicate with the laravel server. Don't know how to do that.

我发现类似的stackoverflow问题,但是他们的回答并不能解决我的问题。我发现的最好的事情是,它建议使用Laravel护照。但是,提案是唯一可行的提案吗?如果是这样,Laravel通行证是否可以保护用户免受CSRF攻击?

I found similiar stackoverflow questions, but the responses from them do not solve my problem. The best thing I found was this, which proposes to use Laravel passport. But, is the proposal the only one that works? If so, does Laravel passport protect users from CSRF attacks?

实际上,如果有一种变通办法可以在保护CSRF令牌的同时将后端和前端分开,那么那将是完美的!

Actually, if there is an workaround which enables to have separated backend and frontend while protecting against CSRF tokens, then that would be perfect!

推荐答案

使用圣殿


  1. 通过Composer安装圣殿

    撰写者需要laravel / sanctum






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

    php artisan供应商:publish --provider =" Laravel\ Sanctum\SanctumServiceProvider;






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

    php artisan migration






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

$中的 api 中间件组b $ b




use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

'api' => [
    EnsureFrontendRequestsAreStateful::class,
    'throttle:60,1',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],



  1. 配置SPA将从哪个域发出请求。从文档中:



您可以在圣所中使用有状态配置选项来配置这些域配置文件。该配置设置确定哪些域将保持有状态状态。向API发出请求时使用Laravel会话cookie进行身份验证。

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

So - Update your config\sanctum.php to include something like this:

/*
    |--------------------------------------------------------------------------
    | 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 ,添加以下内容:

  1. In your .env, add the following:





// 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 FRONTEND



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

  1. In your front-end, create the following folder/file structure @/src/services/api.js

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 文件,其中应包含以下内容:

In the root directory, place an .env file with the following in it:

VUE_APP_API_URL= 'http://api.your-site.local'  



  1. 要进行身份验证,您的SPA应该首先向 / sanctum / csrf-cookie 。这将设置 XSRF-TOKEN cookie。此令牌需要在后续请求中发送(axios将自动为您处理)。之后,您将要向您的Laravel / login 路由发送 POST 请求。

  1. To authenticate, your SPA should first make a request to the /sanctum/csrf-cookie. This sets the XSRF-TOKEN cookie. This token needs to be sent on subsequent requests ( axios will handle this for you automatically ). Immediately after, you'll want to send a POST request to your Laravel /login route.


在您的Vue前端登录组件上:



On your Vue front-end login component:


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;
    },

  },

这篇关于如何使用分离的vue前端检索Laravel CSRF令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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