code

사용자가 로그인 한 후 Laravel 5 세션이 지속되지 않음

codestyles 2020. 12. 2. 21:22
반응형

사용자가 로그인 한 후 Laravel 5 세션이 지속되지 않음


Laravel 5에 흥미로운 문제가 있습니다.

사용자 로그인 후 로그인 상태는 페이지에서 유지되지 않습니다. 분명히 그것은와 관련이 있습니다 Session::.

사용자 로그인 방식은 매우 간단합니다.

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

print_r(Session::all());사용자가 로그인하지 않은 경우 간단한 방법 은 다음과 같습니다.

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

            [new] => Array
                (
                )

        )

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

)

사용자가 로그인 /하면 다음과 같이 배열 로 리디렉션됩니다 .

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

            [new] => Array
                (
                )

        )

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

    [login_82e5d2c56bdd0811318f0cf078b78bfc] => 2
)

그러나 페이지 새로 고침 또는 리디렉션으로 이어지는 작업 후에는 세션 상태가 손실됩니다.

config/session.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,

];

세션에 대해 로컬로 저장된 파일을 쓰고 읽을 수 있습니다.

database파일 대신 드라이브를 사용해 보았습니다 . 같은 일이 발생 [login_xx] => 2키 / 값이 손실되고 내가 로그 아웃하고 있습니다.

Session::이 완전히 재설정되지 않았기 때문에 사용자가 제대로 로그인하지 않았거나 단순히 어딘가에서해서는 안되는 일을하고 있다고 생각합니다.


비슷한 문제에 직면하여 간단히 전화했습니다.

Session::save();

세션 스토리지에 대한 추가 / 업데이트 / 삭제 후. 그래서 다음과 같이 보였습니다.

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

나는 같은 문제가 있었다. dd () 및 print_r ()의 다양한 조합을 제거하고 테스트 목적으로 응답을 덤프하는 데 사용하고 메서드가 뷰를 완료하고 완전히 렌더링하도록 허용하면 문제가 사라지고 세션이 지속되었습니다.


나는 변화를 해결했다

'cookie' => 'laravel_session',

...에

'cookie' => 'myapp_session',

laravel에 따르면 쿠키의 이름은 모든 운전자에게 영향을 미칩니다.


나는 Laravel에 익숙하지 않지만 CodeIgniter에서 사용자 세션을 CI의 세션 클래스에 저장하고 Laravel도 하나 있습니다.

기본 $ _SESSION보다 더 영구적 인 내장 세션 을 사용하는 것이 좋습니다. 아마도 데이터베이스에 사용자 데이터를 저장하고 각 페이지 새로 고침 / 변경시 세션이 DB에서 다시 채워집니다.

사용자가 인증 할 때 다음과 같이 세션 데이터를 저장하십시오.

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

... 값은 부울 값이거나 사용자 특정 데이터를 보유하는 전체 개체 일 수 있습니다.

각 페이지로드시 세션에서 사용자 데이터를 가져옵니다.

$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';

편집 : 인증 클래스를 사용하는 것을 확인했습니다. 내 대답은 대부분 사용자의 수동 로그인이며 작동합니다.
인증 클래스가 기본적으로이 작업을 수행해야한다고 생각하지만 구성이 누락되었거나 버그가있을 수 있습니다.

가능한 해결책은 다음과 같습니다 (Laravel 4이지만 시도해 볼 가치가 있습니다) : http://laravel.io/forum/11-11-2014-authcheck-always-returning-false

최신 정보:

현재 당신의 드라이버 값을 변경하려고합니다

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

...에

'driver' => 'file'

... 또한 Laravel의 문서에서 드라이버가 이와 같이 정의되어야 함을 알 수 있습니다.


먼저 로그 아웃을 유발하는 사전 필터, 미들웨어 또는 라우트 그룹이 없는지 확인하십시오. 적어도 일시적으로 Auth :: logout ()을 검색하고 주석 처리하십시오. 나는 이것이 문제라는 것을 두 번 이상 보았다.

둘째,이 통화를 올바르게하고있는 것 같습니다. 세 번째 매개 변수는 $ login : bool이며 기본값은 true입니다. 이것은 귀하의 문제는 아니지만 PSR-1 / 2 표준을 충족하려면 TRUE 및 FALSE를 true 및 false로 변경하십시오.

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().


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.

  1. The session directory ie storage/framework/session/ is writable.
  2. The routes for logging in maybe (/login) and for checking authentication (maybe /dashboard) are all within the group web

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.


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

For exemple in Debian system:

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. service ntp start
  3. date (normally the date and hour are corrected)

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.


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.


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.

And now is working

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

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

                }

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


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.


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:

'domain' => null,

after that clear your cookies:

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


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

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

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',
    ],
];

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

So, instead of doing:

loginUsingId(1);

You should do

loginUsingId(1, true);

See docs

참고URL : https://stackoverflow.com/questions/30769434/laravel-5-session-not-persisting-after-user-is-logged-in

반응형