Laravel Inertia (Vue) - аутентификация без перенаправления

Я делаю обычный пост Inertia для базового маршрута входа в Laravel:

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

Я могу улавливать ошибки проверки, как и ожидалось, но я пытаюсь избежать перенаправления после успешной аутентификации пользователя и вместо этого продолжаю работу в состоянии входа в систему (обновите заголовок для отображения информации о пользователе и т. Д.).

Типаж Laravel AuthenticatesUsers содержит два ключевых метода, которые вызываются как часть готового процесса входа в систему.

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());
    }

Я изо всех сил пытаюсь понять, можно ли вообще аутентифицировать пользователя без перенаправления таким образом.


person iamnull90    schedule 07.07.2020    source источник


Ответы (2)


Вам нужно использовать интерфейс 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);
    });
person Lux Ilustre    schedule 05.02.2021

Проверьте свою форму и способ отправки - предотвращаете ли вы поведение отправки формы по умолчанию? Похоже, вы отправляете POST, но также срабатывает собственное поведение формы.

Вы также можете установить $redirectTo в своем LoginController, также проверьте RouteServiceProvider, есть ли public const HOME = '/', который инициировал перенаправление, если больше ничего не указано.

person lost.design    schedule 11.08.2020