Laravel 5会话在用户登录后不会持续

时间:2022-05-02 12:58:02

I'm having an interesting issue with Laravel 5.

我和Laravel 5有个有趣的话题。

After logging in a user, the logged in status is not persisted across pages. Clearly it has something to do with Session::.

登录用户后,登录状态不会跨页面持久化。显然,这与会话有关:。

The way I'm logging in a user is pretty straight-forward:

我登录用户的方式非常直接:

if (Auth::attempt(['email' => $data['email'], 'password' => $data['password']],
    isset($data['remember_me']) ? TRUE : FALSE))
{
    return redirect()->intended('/');
}

A simple print_r(Session::all()); gives me the following if the user is NOT logged in:

一个简单的print_r(会话:所有());如果用户没有登录,则给我以下信息:

Array
(
    [_token] => wV8o75lZnCZ0f6CMMQgdBBM2AxSYjtWisAXx6TgZ
    [flash] => Array
        (
            [old] => Array
                (
                )

            [new] => Array
                (
                )

        )

    [_previous] => Array
        (
            [url] => http://localhost/public
        )

)

After the user is logged in an redirected to / the array looks like this:

在用户被重定向到/该数组后,如下所示:

Array
(
    [_token] => wV8o75lZnCZ0f6CMMQgdBBM2AxSYjtWisAXx6TgZ
    [flash] => Array
        (
            [old] => Array
                (
                )

            [new] => Array
                (
                )

        )

    [_previous] => Array
        (
            [url] => http://localhost/public/
        )

    [login_82e5d2c56bdd0811318f0cf078b78bfc] => 2
)

However, after any action that will lead to a page refresh or a redirect, the session status is lost.

但是,在任何导致页面刷新或重定向的操作之后,会话状态将丢失。

My config/session.php file looks like so:

我的配置/会话。php文件如下:

<?php

return [
    'driver' => env('SESSION_DRIVER', 'file'),
    'lifetime' => 120,
    'expire_on_close' => false,
    'encrypt' => false,
    'files' => storage_path('framework/sessions'),
    'connection' => null,
    'table' => 'sessions',
    'lottery' => [2, 100],
    'cookie' => 'laravel_session',
    'path' => '/',
    'domain' => null,
    'secure' => false,

];

The locally stored file for the session can be written and read.

会话的本地存储文件可以被写入和读取。

I've tried using database drive instead of file. Same thing happens the [login_xx] => 2 key/value is lost and I'm logged out.

我试过用数据库驱动代替文件。同样的事情发生了,[login_xx] => 2键/值丢失,我被注销。

Since the Session:: is not completely reset I'm suspecting that I'm not logging in the user properly or simply doing something that I shouldn't be doing somewhere.

由于会话:没有完全重置,我怀疑我没有正确地登录用户,或者只是做一些我不应该在某些地方做的事情。

15 个解决方案

#1


12  

I faced similar issue, I simply called:

我也遇到过类似的问题,我简单地说:

Session::save();

after any add/update/delete to Session storage. So it looked like:

在任何添加/更新/删除到会话存储之后。所以它看起来像:

$id = Input::get('id');
Session::forget('cart.' .$id);
Session::save();

#2


7  

I had the same issue. Once I removed the various combinations of dd() and print_r() I was using to dump responses for testing purposes and allowed the method to complete and fully render the view, the issue went away and sessions persisted.

我也有同样的问题。为了测试目的,我删除了用于转储响应的dd()和print_r()的各种组合,并允许方法完成并完全呈现视图,问题就消失了,会话也继续存在。

#3


4  

I solved changing

我解决了改变

'cookie' => 'laravel_session',

to

'cookie' => 'myapp_session',

according to laravel the name of the cookie affects every driver

根据laravel的说法,cookie的名字会影响到每个驱动程序

#4


1  

I'm not familiar with Laravel, but on CodeIgniter I save user session in CI's Session Class and Laravel has one too.

我不熟悉Laravel,但在CodeIgniter上,我将用户会话保存在CI的会话类中,Laravel也有一个。

I suggest to use the build-in session which is more persistent than default $_SESSION - probably it saves user data in database and on each page refresh/change the session is populated again from DB.

我建议使用内置会话,它比默认的$_SESSION更持久——它可能会在数据库中保存用户数据,并且在每个页面刷新/更改时,会话将再次从DB中填充。

When user authenticates, just save its session data like this:

当用户进行身份验证时,只需将其会话数据保存如下:

Session::put('userData', 'value');

...where value could be just a boolean value or an entire object that holds user specific data.

…值可以是布尔值,也可以是保存用户特定数据的整个对象。

On each page load, get user data from session:

在每个页面加载中,从会话获取用户数据:

$user = Session::get('userData');

if($user->id) echo 'user is logged-in'; //or if($user) - depends on what you store in 'userData' key
else echo 'guest only privilegies';

EDIT: I see that you use the Auth Class. My answer is mostly for manual login of the user and it works.
I think that the Auth Class should be doing this by default, but probably you're missing some configuration or there's a bug.

编辑:我看到你使用的是Auth类。我的回答主要是用户的手动登录,它是有效的。我认为Auth类在默认情况下应该这样做,但是您可能丢失了一些配置,或者有一个bug。

Here's a possible solution (Laravel 4, but it worths a try): http://laravel.io/forum/11-11-2014-authcheck-always-returning-false

这里有一个可能的解决方案(Laravel 4,但值得一试):http://laravel.io/forum/11-11-11-11-2014-authcheck -alway -returning-false

Update:

As of this you should try to change the driver value from

至此,您应该尝试更改驱动程序的值

'driver' => env('SESSION_DRIVER', 'file')

to

'driver' => 'file'

...also on Laravel's docs you can see that the driver has to be defined like that.

…在Laravel的文档中,你可以看到驱动必须这样定义。

#5


1  

First, make sure you don't have some sort of a before filter, middleware, or route group that is causing them to be logged out. At least temporarily, search for any Auth::logout() and comment it out. I have seen this be the problem more than once.

首先,要确保在筛选器、中间件或路由组之前没有某种类型的过滤器,从而导致它们被注销。至少暂时搜索任何Auth::logout()并注释掉它。我不止一次地看到这个问题。

Second, you look like you're doing this call correctly. The third parameter is $login : bool and it defaults to true. This is not your problem, but please change your TRUE and FALSE to true and false to meet with PSR-1/2 standards.

第二,你看起来是正确的。第三个参数是$login: bool,它默认为true。这不是你的问题,但请将你的真与假改为真与假,以符合PSR-1/2标准。

I would have advised that you try another driver, but you have done that and have the same result. This leads me to think that you have some sort of earlier code that is misdirecting to a logout().

我建议你尝试另一个驱动程序,但你已经这样做了,并且得到了相同的结果。这使我认为您有一些早期的代码错误指向注销()。

#6


1  

You need to make sure of 2 things if you are using default laravel's file session which you can check if you are using in session.php file.

如果您使用的是laravel的默认文件会话,那么您需要确保有两件事情,您可以在会话中检查是否使用这个文件会话。php文件。

  1. The session directory ie storage/framework/session/ is writable.
  2. 会话目录ie storage/framework/session/是可写的。
  3. The routes for logging in maybe (/login) and for checking authentication (maybe /dashboard) are all within the group web
  4. 登录maybe (/login)和检查身份验证(maybe /dashboard)的路由都在组web中

ie.

ie。

Route::group(['middleware' => ['web']], function () {
   Route::get('/home/login', ['as' => 'login', 'uses' => 'HomeController@getLogin']);
Route::post('/home/login', ['as' => 'login', 'uses' => 'HomeController@postLogin']);
   Route::get('/home/dashboard', ['as' => 'home', 'uses' => 'HomeController@getDashboard']);
}

This worked for me in Laravel 5.

这在Laravel 5里对我很管用。

#7


0  

correctedHum... Ensure your machine is setted with good date and hour, and equally the other machines on the network who working with.

correctedHum……确保您的机器具有良好的日期和时间,以及网络上与您一起工作的其他机器。

For exemple in Debian system:

以Debian系统为例:

In the command prompt, hit date (you will see the date), if it's not correct follow these instructions:

在命令提示符中,点击日期(您将看到日期),如果不正确,请遵循以下说明:

  1. apt-get install ntp
  2. apt-get安装国家结核控制规划
  3. service ntp start
  4. 服务国家结核控制规划开始
  5. date (normally the date and hour are corrected)
  6. 日期(通常更正日期和时间)

#8


0  

Use "cookie" driver instead of "file" of session.php (config\session.php\driver). I had a problem with login using "Auth::loginUsingId()" api instead of "Auth::attempt()" api, it destroyed the session for another request.

使用“cookie”驱动程序而不是会话的“file”。php(config \ session.php \驱动程序)。我在使用“Auth::loginUsingId()”api而不是“Auth:: try()”api登录时遇到了问题,它破坏了另一个请求的会话。

#9


0  

Make sure that the target route also uses the middleware StartSession. In my "fresh" installation of Laravel 5.2 the "web" middleware group uses it, but the root path (/), which also happens to be the default $redirectTo after login, was outside of it. Huge loss of time.

确保目标路由也使用中间件StartSession。在我的“fresh”安装的Laravel 5.2中,“web”中间件组使用它,但是根路径(/),也碰巧是登录后默认的$redirectTo,是在它之外的。巨大的损失时间。

#10


0  

I had this problem to and i solve this way. After Auth::attemp or Auth::login() dont use echo, var_dump or dd() i dont know why but those prevent to keep the session in the browser.

我有这个问题,我用这种方法解决。在Auth::attemp或Auth: login()之后,不要使用echo、var_dump或dd()。

And now is working

现在是工作

                public function testLogin(Request $request, $id){

                    $user = Account::find($id);
                    Auth::login($user);

                }

#11


0  

I had a similar problem and I have fixed it by changing the Session Driver from SESSION_DRIVER=database to SESSION_DRIVER=file

我有一个类似的问题,我通过将会话驱动从SESSION_DRIVER=database更改为SESSION_DRIVER=file来修复它

#12


0  

In my case I had to change the domain setting in the app/config/sessions.php file. I had a different domain written there instead of the one that I was using and naturally it didn't work. Though I don't understand why the framework went ahead and created the session files each time I was reloading the page.

在我的情况下,我必须更改应用程序/配置/会话中的域设置。php文件。我有一个不同的领域写在那里而不是我正在使用的,自然它不起作用。尽管我不理解为什么每次重载页面时框架都要继续创建会话文件。

#13


0  

I had the same issue, but it has been fixed now.

我有同样的问题,但现在已经解决了。

It's because of the conflict between sessions in your machine and in your localhost domain. To solve the problem:

这是因为您的机器中的会话与本地主机域中的会话之间存在冲突。解决的问题:

First of all check your config/session.php file and check this:

首先检查配置/会话。php文件,检查如下:

'domain' => null,

after that clear your cookies:

清理完饼干后:

on Firefox, right click -> view page info -> Security -> View Cookies -> Remove all

在Firefox上,右键单击->查看页面信息->安全性->查看cookie ->删除所有

#14


0  

i had the same problem in laravel 5.4, the solution for me was:

我在laravel 5.4中遇到了同样的问题,我的解决方案是:

In the file /app/Http/Kernel.php, was commented middleware AuthenticateSession by default.

在文件/程序/ Http /内核。php,默认情况下是中间件身份验证切换。

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        //\Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

Only uncommented this line and the session work fine in all routes

只有未注释的这一行和会话在所有路由中都可以正常工作

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

#15


0  

If you are using loginUsingId() method you should set 'remember' flag to true.

如果您正在使用loginUsingId()方法,您应该将“remember”标志设置为true。

So, instead of doing:

因此,而不是做:

loginUsingId(1);

You should do

你应该做的

loginUsingId(1, true);

See docs

看文档

#1


12  

I faced similar issue, I simply called:

我也遇到过类似的问题,我简单地说:

Session::save();

after any add/update/delete to Session storage. So it looked like:

在任何添加/更新/删除到会话存储之后。所以它看起来像:

$id = Input::get('id');
Session::forget('cart.' .$id);
Session::save();

#2


7  

I had the same issue. Once I removed the various combinations of dd() and print_r() I was using to dump responses for testing purposes and allowed the method to complete and fully render the view, the issue went away and sessions persisted.

我也有同样的问题。为了测试目的,我删除了用于转储响应的dd()和print_r()的各种组合,并允许方法完成并完全呈现视图,问题就消失了,会话也继续存在。

#3


4  

I solved changing

我解决了改变

'cookie' => 'laravel_session',

to

'cookie' => 'myapp_session',

according to laravel the name of the cookie affects every driver

根据laravel的说法,cookie的名字会影响到每个驱动程序

#4


1  

I'm not familiar with Laravel, but on CodeIgniter I save user session in CI's Session Class and Laravel has one too.

我不熟悉Laravel,但在CodeIgniter上,我将用户会话保存在CI的会话类中,Laravel也有一个。

I suggest to use the build-in session which is more persistent than default $_SESSION - probably it saves user data in database and on each page refresh/change the session is populated again from DB.

我建议使用内置会话,它比默认的$_SESSION更持久——它可能会在数据库中保存用户数据,并且在每个页面刷新/更改时,会话将再次从DB中填充。

When user authenticates, just save its session data like this:

当用户进行身份验证时,只需将其会话数据保存如下:

Session::put('userData', 'value');

...where value could be just a boolean value or an entire object that holds user specific data.

…值可以是布尔值,也可以是保存用户特定数据的整个对象。

On each page load, get user data from session:

在每个页面加载中,从会话获取用户数据:

$user = Session::get('userData');

if($user->id) echo 'user is logged-in'; //or if($user) - depends on what you store in 'userData' key
else echo 'guest only privilegies';

EDIT: I see that you use the Auth Class. My answer is mostly for manual login of the user and it works.
I think that the Auth Class should be doing this by default, but probably you're missing some configuration or there's a bug.

编辑:我看到你使用的是Auth类。我的回答主要是用户的手动登录,它是有效的。我认为Auth类在默认情况下应该这样做,但是您可能丢失了一些配置,或者有一个bug。

Here's a possible solution (Laravel 4, but it worths a try): http://laravel.io/forum/11-11-2014-authcheck-always-returning-false

这里有一个可能的解决方案(Laravel 4,但值得一试):http://laravel.io/forum/11-11-11-11-2014-authcheck -alway -returning-false

Update:

As of this you should try to change the driver value from

至此,您应该尝试更改驱动程序的值

'driver' => env('SESSION_DRIVER', 'file')

to

'driver' => 'file'

...also on Laravel's docs you can see that the driver has to be defined like that.

…在Laravel的文档中,你可以看到驱动必须这样定义。

#5


1  

First, make sure you don't have some sort of a before filter, middleware, or route group that is causing them to be logged out. At least temporarily, search for any Auth::logout() and comment it out. I have seen this be the problem more than once.

首先,要确保在筛选器、中间件或路由组之前没有某种类型的过滤器,从而导致它们被注销。至少暂时搜索任何Auth::logout()并注释掉它。我不止一次地看到这个问题。

Second, you look like you're doing this call correctly. The third parameter is $login : bool and it defaults to true. This is not your problem, but please change your TRUE and FALSE to true and false to meet with PSR-1/2 standards.

第二,你看起来是正确的。第三个参数是$login: bool,它默认为true。这不是你的问题,但请将你的真与假改为真与假,以符合PSR-1/2标准。

I would have advised that you try another driver, but you have done that and have the same result. This leads me to think that you have some sort of earlier code that is misdirecting to a logout().

我建议你尝试另一个驱动程序,但你已经这样做了,并且得到了相同的结果。这使我认为您有一些早期的代码错误指向注销()。

#6


1  

You need to make sure of 2 things if you are using default laravel's file session which you can check if you are using in session.php file.

如果您使用的是laravel的默认文件会话,那么您需要确保有两件事情,您可以在会话中检查是否使用这个文件会话。php文件。

  1. The session directory ie storage/framework/session/ is writable.
  2. 会话目录ie storage/framework/session/是可写的。
  3. The routes for logging in maybe (/login) and for checking authentication (maybe /dashboard) are all within the group web
  4. 登录maybe (/login)和检查身份验证(maybe /dashboard)的路由都在组web中

ie.

ie。

Route::group(['middleware' => ['web']], function () {
   Route::get('/home/login', ['as' => 'login', 'uses' => 'HomeController@getLogin']);
Route::post('/home/login', ['as' => 'login', 'uses' => 'HomeController@postLogin']);
   Route::get('/home/dashboard', ['as' => 'home', 'uses' => 'HomeController@getDashboard']);
}

This worked for me in Laravel 5.

这在Laravel 5里对我很管用。

#7


0  

correctedHum... Ensure your machine is setted with good date and hour, and equally the other machines on the network who working with.

correctedHum……确保您的机器具有良好的日期和时间,以及网络上与您一起工作的其他机器。

For exemple in Debian system:

以Debian系统为例:

In the command prompt, hit date (you will see the date), if it's not correct follow these instructions:

在命令提示符中,点击日期(您将看到日期),如果不正确,请遵循以下说明:

  1. apt-get install ntp
  2. apt-get安装国家结核控制规划
  3. service ntp start
  4. 服务国家结核控制规划开始
  5. date (normally the date and hour are corrected)
  6. 日期(通常更正日期和时间)

#8


0  

Use "cookie" driver instead of "file" of session.php (config\session.php\driver). I had a problem with login using "Auth::loginUsingId()" api instead of "Auth::attempt()" api, it destroyed the session for another request.

使用“cookie”驱动程序而不是会话的“file”。php(config \ session.php \驱动程序)。我在使用“Auth::loginUsingId()”api而不是“Auth:: try()”api登录时遇到了问题,它破坏了另一个请求的会话。

#9


0  

Make sure that the target route also uses the middleware StartSession. In my "fresh" installation of Laravel 5.2 the "web" middleware group uses it, but the root path (/), which also happens to be the default $redirectTo after login, was outside of it. Huge loss of time.

确保目标路由也使用中间件StartSession。在我的“fresh”安装的Laravel 5.2中,“web”中间件组使用它,但是根路径(/),也碰巧是登录后默认的$redirectTo,是在它之外的。巨大的损失时间。

#10


0  

I had this problem to and i solve this way. After Auth::attemp or Auth::login() dont use echo, var_dump or dd() i dont know why but those prevent to keep the session in the browser.

我有这个问题,我用这种方法解决。在Auth::attemp或Auth: login()之后,不要使用echo、var_dump或dd()。

And now is working

现在是工作

                public function testLogin(Request $request, $id){

                    $user = Account::find($id);
                    Auth::login($user);

                }

#11


0  

I had a similar problem and I have fixed it by changing the Session Driver from SESSION_DRIVER=database to SESSION_DRIVER=file

我有一个类似的问题,我通过将会话驱动从SESSION_DRIVER=database更改为SESSION_DRIVER=file来修复它

#12


0  

In my case I had to change the domain setting in the app/config/sessions.php file. I had a different domain written there instead of the one that I was using and naturally it didn't work. Though I don't understand why the framework went ahead and created the session files each time I was reloading the page.

在我的情况下,我必须更改应用程序/配置/会话中的域设置。php文件。我有一个不同的领域写在那里而不是我正在使用的,自然它不起作用。尽管我不理解为什么每次重载页面时框架都要继续创建会话文件。

#13


0  

I had the same issue, but it has been fixed now.

我有同样的问题,但现在已经解决了。

It's because of the conflict between sessions in your machine and in your localhost domain. To solve the problem:

这是因为您的机器中的会话与本地主机域中的会话之间存在冲突。解决的问题:

First of all check your config/session.php file and check this:

首先检查配置/会话。php文件,检查如下:

'domain' => null,

after that clear your cookies:

清理完饼干后:

on Firefox, right click -> view page info -> Security -> View Cookies -> Remove all

在Firefox上,右键单击->查看页面信息->安全性->查看cookie ->删除所有

#14


0  

i had the same problem in laravel 5.4, the solution for me was:

我在laravel 5.4中遇到了同样的问题,我的解决方案是:

In the file /app/Http/Kernel.php, was commented middleware AuthenticateSession by default.

在文件/程序/ Http /内核。php,默认情况下是中间件身份验证切换。

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        //\Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

Only uncommented this line and the session work fine in all routes

只有未注释的这一行和会话在所有路由中都可以正常工作

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

#15


0  

If you are using loginUsingId() method you should set 'remember' flag to true.

如果您正在使用loginUsingId()方法,您应该将“remember”标志设置为true。

So, instead of doing:

因此,而不是做:

loginUsingId(1);

You should do

你应该做的

loginUsingId(1, true);

See docs

看文档