我有一个使用 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() 函数来登录用户。