如何在 Laravel Inertia 上全域新增 _token csrf?
P粉608647033
P粉608647033 2023-12-10 20:51:46
0
1
600

我有一個使用 Laravel Inertia 和 Vue Js 的專案。這些天我遇到了 csrf 令牌的問題。我已經閱讀了這裡的文檔 https://inertiajs.com/csrf-protection,所以也許我應該在每個慣性請求/回應上新增 csrf 令牌。

我的問題是,如何全域加入這個_token?所以我不需要一一添加token到我的vue檔案中,因為它的檔案太多了。

我目前在login.vue上的腳本程式碼:

props: {
        errors: Object,
        session: Object,
        auth: Array
    },

    //define composition API
    setup(props) {
        //define form state
        const form = reactive({
            email: '',
            password: '',
        });

        //submit method
        const submit = () => {

            //send data to server
            Inertia.post('/login', {

                //data
                email: form.email,
                password: form.password,
                _token: props.auth.csrf
            });
        }

我的 HandleInertiaRequest(中間件):

<?php

namespace AppHttpMiddleware;

use IlluminateHttpRequest;
use InertiaMiddleware;

class HandleInertiaRequests extends Middleware
{
    /**
     * The root template that's loaded on the first page visit.
     *
     * @see https://inertiajs.com/server-side-setup#root-template
     * @var string
     */
    protected $rootView = 'app';

    /**
     * Determines the current asset version.
     *
     * @see https://inertiajs.com/asset-versioning
     * @param  IlluminateHttpRequest  $request
     * @return string|null
     */
    public function version(Request $request): ?string
    {
        return parent::version($request);
    }

    /**
     * Defines the props that are shared by default.
     *
     * @see https://inertiajs.com/shared-data
     * @param  IlluminateHttpRequest  $request
     * @return array
     */
    public function share(Request $request): array
    {
        return array_merge(parent::share($request), [
            //session
            'session' => [
                'status'    => fn () => $request->session()->get('status'),
                'success'   => fn () => $request->session()->get('success'),
                'error'     => fn () => $request->session()->get('error'),
            ],
            //user authenticated
            'auth' => [
                'user'          => $request->user() ?   $request->user() : null,
                'permissions'   => $request->user() ? $request->user()->getPermissionArray() : [],
                'csrf' => $request->session()->token()
            ],
            //route
            'route' => function () use ($request) {
                return [
                    'params' => $request->route()->parameters(),
                    'query' => $request->all(),
                ];
            },
        ]);
    }
}


#
P粉608647033
P粉608647033

全部回覆(1)
P粉794851975

在您的 Middleware/HandleInertiaRequests.php 檔案中全域新增 csrf 令牌。

/**
 * Defines the props that are shared by default.
 *
 * @see https://inertiajs.com/shared-data
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function share(Request $request): array
{
    return array_merge(parent::share($request), [
          'csrf_token' => csrf_token(),
    ]);
}

在您的表單中新增實例。

<input type="hidden" name="_token" :value="this.$page.props.csrf_token">

最後,進行調用,在下面的範例中,我使用 Inertia useForm() 函數來登入使用者。

<script setup>
  import { useForm } from '@inertiajs/vue3'

  const form = useForm({
    email: String,
    password: String,
    _token: String,
    processing: false,
  });

  let submit = () => {
    form.processing = true
    
    form.post('/login')
  }
</script>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板