我有一個使用 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(), ]; }, ]); } }
在您的
Middleware/HandleInertiaRequests.php
檔案中全域新增 csrf 令牌。在您的表單中新增實例。
最後,進行調用,在下面的範例中,我使用 Inertia useForm() 函數來登入使用者。