#php #laravel #session #laravel-7
#php #laravel #сеанс #laravel-7
Вопрос:
У меня проблема с аутентификацией laravel.
Через некоторое время аутентифицированный пользователь меняется на случайный. Клиент использует один и тот же Интернет для 3 устройств (пользователей) в одной сети для использования сайта, и эта конкретная ошибка появляется, когда они параллельно открывают две вкладки и используют сайт — пользователь на одной вкладке изменится на пользователя, который находится в этих трех, или даже более странный — пользователь сустройство, которое находится в другой сети, и они получат код состояния 419.
Я создал cronjob для команды optimize: clear для запуска 2 / час. Примечание: это происходит только на рабочем сервере — я безуспешно пытался воспроизвести это локально. Ниже приведен мой контроллер входа в систему, который использует trait https://laravel.com/api/6.x/Illuminate/Foundation/Auth/AuthenticatesUsers.html из laravel 6.x, хотя моя версия laravel в project равна 7.0. Единственное, что я изменил в trait, — это учетные данные, используемые при входе в систему — вместо электронной почты я использую имя пользователя.
Поскольку у меня нет способа решить эту проблему, любая помощь будет оценена.
<?php
namespace AppHttpControllersAuth;
use AppHttpControllersController;
use AppProvidersRouteServiceProvider;
use IlluminateFoundationAuthAuthenticatesUsers;
use IlluminateFoundationAuthRedirectsUsers;
use IlluminateFoundationAuthThrottlesLogins;
use IlluminateHttpRequest;
use IlluminateHttpResponse;
use IlluminateSupportFacadesAuth;
use IlluminateValidationValidationException;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use RedirectsUsers, ThrottlesLogins;
/**
* Show the application's login form.
*
* @return IlluminateViewView
*/
public function showLoginForm()
{
return view('auth.login');
}
/**
* Handle a login request to the application.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpRedirectResponse|IlluminateHttpResponse|IlluminateHttpJsonResponse
*
* @throws IlluminateValidationValidationException
*/
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') amp;amp;
$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);
}
/**
* Validate the user login request.
*
* @param IlluminateHttpRequest $request
* @return void
*
* @throws IlluminateValidationValidationException
*/
protected function validateLogin(Request $request)
{
$request->validate([
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
/**
* Attempt to log the user into the application.
*
* @param IlluminateHttpRequest $request
* @return bool
*/
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), $request->filled('remember')
);
}
/**
* Get the needed authorization credentials from the request.
*
* @param IlluminateHttpRequest $request
* @return array
*/
protected function credentials(Request $request)
{
return $request->only($this->username(), 'password');
}
/**
* Send the response after the user was authenticated.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
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());
}
/**
* The user has been authenticated.
*
* @param IlluminateHttpRequest $request
* @param mixed $user
* @return mixed
*/
protected function authenticated(Request $request, $user)
{
$mode = $user->viewmode;
return redirect()->route($mode . '-mode');
}
/**
* Get the failed login response instance.
*
* @param IlluminateHttpRequest $request
* @return SymfonyComponentHttpFoundationResponse
*
* @throws IlluminateValidationValidationException
*/
protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
]);
}
/**
* Get the login username to be used by the controller.
*
* @return string
*/
public function username()
{
return 'username';
}
/**
* Log the user out of the application.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
if ($response = $this->loggedOut($request)) {
return $response;
}
return $request->wantsJson()
? new Response('', 204)
: redirect('/');
}
/**
* The user has logged out of the application.
*
* @param IlluminateHttpRequest $request
* @return mixed
*/
protected function loggedOut(Request $request)
{
//
}
/**
* Get the guard to be used during authentication.
*
* @return IlluminateContractsAuthStatefulGuard
*/
protected function guard()
{
return Auth::guard();
}
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
Комментарии:
1. используя тот же интернет… вы имеете в виду использование одного и того же компьютера и браузера? это ожидаемое поведение
2. я отредактировал вопрос — это 3 пользователя на 3 разных устройствах в одной сети