Laravel Auth: попытка() не будет продолжаться.
Я нашел много ресурсов в Интернете с похожими проблемами, но ни одно из решений, похоже, не решило мою проблему.
Когда я регистрирую пользователя со следующим кодом, все выглядит нормально:
$email = Input::get('email');
$password = Input::get('password');
if (Auth::attempt(array('email' => $email, 'password' => $password))) {
return Auth::user();
} else {
return Response::make("Invalid login credentials, please try again.", 401);
}
Функция Auth::attempt()
возвращает true
, и пользователь, зарегистрированный в системе, возвращается клиенту с помощью Auth::user()
.
Но если клиент делает другой запрос непосредственно на сервер, Auth::user()
возвращает NULL
.
Я подтвердил, что сеансы Laravel работают правильно, успешно используя Session::put()
и Session::get()
.
Update
В ходе дальнейшего расследования выясняется, что сеансы также не сохраняются! Может ли это быть связано с тем, что сервер веб-приложений AngularJS через app.mydomain.com и API Laravel обслуживается через api.mydomain.com?
Моя модель пользователя выглядит следующим образом:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model JSON form.
*
* @var array
*/
protected $hidden = array('password');
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* @return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
Моя конфигурация auth выглядит следующим образом:
<?php
return array(
/*
|--------------------------------------------------------------------------
| Default Authentication Driver
|--------------------------------------------------------------------------
|
| This option controls the authentication driver that will be utilized.
| This driver manages the retrieval and authentication of the users
| attempting to get access to protected areas of your application.
|
| Supported: "database", "eloquent"
|
*/
'driver' => 'eloquent',
/*
|--------------------------------------------------------------------------
| Authentication Model
|--------------------------------------------------------------------------
|
| When using the "Eloquent" authentication driver, we need to know which
| Eloquent model should be used to retrieve your users. Of course, it
| is often just the "User" model but you may use whatever you like.
|
*/
'model' => 'User',
/*
|--------------------------------------------------------------------------
| Authentication Table
|--------------------------------------------------------------------------
|
| When using the "Database" authentication driver, we need to know which
| table should be used to retrieve your users. We have chosen a basic
| default value but you may easily change it to any table you like.
|
*/
'table' => 'users',
/*
|--------------------------------------------------------------------------
| Password Reminder Settings
|--------------------------------------------------------------------------
|
| Here you may set the settings for password reminders, including a view
| that should be used as your password reminder e-mail. You will also
| be able to set the name of the table that holds the reset tokens.
|
| The "expire" time is the number of minutes that the reminder should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
Миграция, используемая для создания таблицы users
, выглядит следующим образом:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('email')->unique();
$table->string('password');
$table->string('first_name');
$table->string('last_name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function(Blueprint $table)
{
//
});
}
}
И конфигурация сеанса:
<?php
return array(
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "array"
|
*/
'driver' => 'database',
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/
'lifetime' => 120,
'expire_on_close' => false,
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
'files' => storage_path().'/sessions',
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => null,
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
'table' => 'sessions',
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => array(2, 100),
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => 'laravel_session',
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
'path' => '/',
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
'domain' => null,
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you if it can not be done securely.
|
*/
'secure' => false,
);
Любые идеи?
Ответы
Ответ 1
У меня была эта проблема. Изменение первичного ключа для модели пользователя помогло мне.
Попробуйте добавить что-то вроде
protected $primaryKey = 'user_id';
в классе User {} (приложение/модели/User.php)
(Поле user_id
- это ключ автоматического увеличения в моей таблице "Схема для пользователей" )
См. также этот билет: https://github.com/laravel/framework/issues/161
Ответ 2
У меня была эта проблема сегодня утром, и я понял, что когда вы выводите данные перед вызовом
Auth::attempt($credentials);
Тогда вы можете быть уверены, что ваша сессия не будет установлена.
Например, если вы делаете что-то вроде
echo "This is the user " . $user;
чуть выше строки, в которой говорится
Auth::attempt($credentials);
Тогда будьте уверены, что вы потратите все утро, пытаясь найти, почему laravel не продолжает аутентифицированного пользователя и вызывает
Auth::user()
предоставит вам нуль, а также вызовет
Auth::check()
всегда будет давать вам ложь.
Это была моя проблема, и именно так я ее исправил, удалив инструкцию echo.
Ответ 3
Попробуйте передать true
в Auth: попытка() для параметра remember
:
if ( Auth::attempt(array('email' => $email, 'password' => $password), true) ) {
return Auth::user();
} else {
return Response::make("Invalid login credentials, please try again.", 401);
}
Я не уверен, почему вы возвращаете Auth:: user(), хотя.
Ответ 4
У меня была та же проблема в Laravel 5.7. Кто сталкивается с подобными проблемами, если сеанс не сохраняется после аутентификации, может следовать решению, как показано ниже.
Открыть файл App\Http\kernel.php
Переместите \Illuminate\Session\Middleware\StartSession::class,
из protected $middlewareGroups
в protected $middleware
. Это.
Ответ 5
У меня была аналогичная проблема, и в конце концов я был настолько сосредоточен на том, что я не думал, что проблема может быть в интерфейсе.
Я использовал blade-сервер для вывода Auth:logout()
прямо на передний конец, чтобы создать кнопку выхода из системы, например:
<a href="{{Auth::logout()}}">Log out</a>
Это неверно. Каждый раз, когда я вошел в приложение, я был бы перенаправлен на страницу с этой кнопкой, на которую, как я ошибочно думал, назовет Auth::logout()
при нажатии. Конечно, PHP отображается на pageload, а Auth::logout()
вызывается сразу. Затем, когда пользователь переходит на другую страницу, поскольку они были выведены из системы, они перенаправляются на страницу входа в систему, чтобы снова запустить процесс.
FYI. Правильный способ создания кнопки выхода из системы, если вы используете контроллер маршрута Auth по умолчанию, будет направлять на маршрут '/auth/logout', например:
<a href="{{url('/auth/logout')}}">Log Out</a>
Ответ 6
Проблема может заключаться в настройке сеанса. Проверьте, не настроена ли таблица сеансов Laravel для использования драйвера базы данных.
Здесь вы можете увидеть конфигурацию: http://laravel.com/docs/session#database-sessions
Надеюсь, это поможет!
Ответ 7
Сколько времени занимает поле id в вашей таблице сеансов? Laravel использует sha1-хэш как идентификатор сеанса, который дает строку длиной 40. У меня была аналогичная проблема, и это было потому, что в моем поле id было задано значение 32.
Смотрите этот вопрос: Данные сеанса аутентификации Laravel 4.1 не сохраняются в запросах
Ответ 8
Хорошо, я не глубоко вникнул в него, но я понял, что laravel только возвращает файлы cookie через безопасное соединение.
Как вы, должно быть, заметили, laravel настраивает cookie, но не отвечает на продолжительность жизни в session.php
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire when the browser closes, set it to zero.
|
*/
'lifetime' => 60*24*30, //doesn't seem to work ?
Чтобы заставить это работать на вашем локальном сервере, вы должны подражать соединению https, чтобы гарантировать, что логин будет сохранен.
Вы можете сделать это, создав поддельный сертификат/ключ ssl для вашего локального домена.
В Интернете доступно несколько обучающих программ, которые помогут вам включить ssl.
Это может быть полезно:
Как включить SSL в MAMP Pro
MAMP с SSL (https)
Как создать сертификат SSL на Apache для Ubuntu 12.04
Ответ 9
Попробуйте использовать
ob_start();
ob_flush();
перед возвратом или статусом эха;
Пример:
public function login() {
PogfixHelper::$return['ret'] = "error";
$iten = array(
'email' => Input::get("Mail"),
'password' => Input::get("Password"),
'flag_ativo' => 1
);
if (Auth::attempt($iten)) {
PogfixHelper::$return['ret'] = "ok";
PogfixHelper::$return['okMsg'] = "U are in";
PogfixHelper::$return['redirect'] = URL::to('panel/calendar');
} else {
PogfixHelper::$return['errorMsg'] = "Password not match";
}
ob_start();
ob_flush();
echo json_encode(PogfixHelper::$return);
}
Ответ 10
Кстати, используя Laravel 5.7.
У меня была та же проблема, но это было потому, что я пытался использовать их имя пользователя для входа в систему. В случае, если у вас есть пользовательские данные пользователя, помимо адреса email
, name
и password
по умолчанию, и вы не хотите, чтобы они входили через свою email
тогда Вы идете в vendor/laravel/framework/src/Illuminate/Foundation/Auth/
и открываете файл AuthenticatesUsers.php
. В нем есть публичная функция с именем username
:
/**
* Get the login username to be used by the controller.
*
* @return string
*/
public function username()
{
return 'email'; // <----
}
Как видите, по умолчанию установлено 'email'
. Затем вы можете изменить это на то, что вы хотите, чтобы пользователь входил в систему в сочетании со своим паролем. Поэтому для моего сайта я хотел, чтобы пользователь входил под своим username
. Таким образом, вы просто измените его с 'email'
на 'username'
.
Я надеюсь, что это помогает кому-то.
ПРИМЕЧАНИЕ. Достаточно странно, что по какой-то причине он не дал мне ошибок, когда я пытался войти в систему, используя username
и password
. Вместо этого это, казалось бы, подтвердит, но не сохранит пользователя, и я понятия не имею, почему.
Ответ 11
Во-первых, у меня та же проблема на Laravel 5.8.
Я подтверждаю, что решение @nayeem-azad является хорошим, по крайней мере, в моем случае. Одно отличие, в App\Http\kernel.php, я не перемещал эту строку:
\Illuminate\Session\Middleware\StartSession::class
от защищенных $ middlewareGroups к защищенным $ middleware, но копировал его только в защищенное промежуточное ПО.
Надеюсь, поможет ;-)