【问题标题】:Laravel Inertia (Vue) - Authenticate without RedirectLaravel Inertia (Vue) - 无需重定向即可进行身份验证
【发布时间】:2020-10-27 22:57:45
【问题描述】:

我正在向基本 Laravel 登录路径发送普通 Inertia 帖子:

submit() {
      this.$inertia.post("/login", {
        email: this.emailAddress,
        password: this.password,
      }, {
        preserveState: true,
        preserveScroll: true,
      });
}

我能够按预期捕获验证错误,但我试图避免的是成功用户身份验证后的重定向,而是继续进入“登录”状态(更新标题以显示用户信息等)。

Laravel AuthenticatesUsers trait 包含两个关键方法,这些方法在开箱即用的登录流程中被调用

public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if (method_exists($this, 'hasTooManyLoginAttempts') &&
            $this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        if ($response = $this->authenticated($request, $this->guard()->user())) {
            return $response;
        }

        return $request->wantsJson()
                    ? new Response('', 204)
                    : redirect()->intended($this->redirectPath());
    }

我正在努力弄清楚是否甚至可以在不以这种方式重定向的情况下对用户进行身份验证。

【问题讨论】:

    标签: laravel vue.js inertiajs


    【解决方案1】:

    您需要使用 javascript 前端,而不是 Inertia::post() 。一种方法是使用 Axios:

    submit() {
        const data = {...this.form.data()};
        axios.post('/auth/login', data, {
           headers: {
              'Content-Type': 'application/json',
           },
        })
        .then(res => {
           console.log('login success!', res);
        });
    

    【讨论】:

      【解决方案2】:

      检查您的表单和提交方式 - 您是否阻止表单提交的默认行为?似乎您正在发送 POST,但也触发了本机表单行为。

      你也可以在你的 LoginController 中设置一个$redirectTo,同时检查RouteServiceProvider,如果没有给出任何其他信息,有一个public const HOME = '/'会触发重定向。

      【讨论】:

        猜你喜欢
        • 2018-06-18
        • 2021-11-27
        • 2019-09-10
        • 1970-01-01
        • 1970-01-01
        • 2016-07-25
        • 1970-01-01
        • 1970-01-01
        • 2018-09-27
        相关资源
        最近更新 更多