Laravel 5 remember me not working - php

I am unable to get Laravel rememeber me functionality to work.
I added remember token column to my User Model table.
My User Model Authenticatable. User model doesn't contain anything else specific related to remember me functionality
I am using default Auth drivers and guard.
My Usercontroller is different from default one. It extends from Controller. It doesn't use any Traits. In my login method, I use Auth::login($userModelObject, true) to login user. Everything works fine. Remember me token gets updated in database. I can see 3 cookies on browser XSRF-TOKEN, laravel_session, remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d.
Auth::check() returns true as expected but if I either remove, expires, or modify laravel_session, in the subsequent request, remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d cookie also gets removed for some reason (I am not able to view it using var_dump($_COOKIE) in only middleware I applied) and I think that's why Laravel Auth driver isn't able to use remember me Cookie to autologin user. CSRF middleware is also being applied automatically by Framework.
What could be causing this behaviour? Do I need to use some Additional Traits on my User Model or Controller?
Note: I am using Laravel 5.4 and my session config are:
'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => 20,
'expire_on_close' => false,
'encrypt' => false,
'files' => storage_path('framework/sessions'),
'connection' => null,
'table' => 'sessions',
'store' => null,
'lottery' => [2, 100],
'cookie' => 'laravel_session',
'path' => '/',
'domain' => env('SESSION_DOMAIN', null),
'secure' => env('SESSION_SECURE_COOKIE', false),
'http_only' => true

I found the problem. I had this \Illuminate\Session\Middleware\AuthenticateSession::class in Kernel.php. I compared my project with new laravel 5.4 project and found that this is commented out by default. I did that and my problem is fixed now.

Related

Laravel - How to share the session between two or more Web Application?

I have two web Applications. I will login in to one Web Application and will navigate to another by links or redirection from the first Application. Lastly after completing some steps in Application two, I will be redirected to Application one. How can I implement this?
Create a new database called sessions.
Configure a connection profile for the session database secondary to your apps primary databases for both apps.
And then they should be syncing up in storing the data for sessions, being able to share them etc...
config/database.php
'app_main_database' => [
'driver' => env('DB_CONNECTION'),
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
],
'sessions_database' => [
'driver' => env('DB_CONNECTION_SESSION'),
'host' => env('DB_HOST_SESSION'),
'port' => env('DB_PORT_SESSION'),
'database' => env('DB_DATABASE_SESSION'),
'username' => env('DB_USERNAME_SESSION'),
'password' => env('DB_PASSWORD_SESSION'),
],
Configure session.connection to the name for your session driver
config/session.php
<?php
use Illuminate\Support\Str;
return [
'driver' => env('SESSION_DRIVER', 'database'),
'connection' => env('SESSION_CONNECTION', 'sessions_database'),
Your question starts with "Laravel - How do..." which leads me to believe both of your applications are using Laravel. You said they are both on the same server and same domain so you could simply expand the default PHP Session cookie from the SLD (Second Level Domain) scope of yourdomain.com to be a cross subdomain cookie: *.yourdomain.com and then set the same application key and your applications will magically start using the and sharing the data. Just make sure that you did the right work in sharing the user database because Laravel default Auth will take the User ID column and log the user into the same ID.
Make sure the environment variables in the .env for both installations have the same identical settings:
#APP_KEY is used to encrypt the session data so must be the same
APP_KEY=base64:'YOUR KEY '
#SESSION_COOKIE must be the same, this is normally not set and defaults to APP_NAME+"_session' which is a problem if your apps have different names
SESSION_COOKIE=laravel_session
#The SESSION_DOMAIN defaults to null which causes the CORS scope to limit to the subdomain level, in my testing must start with leading dot.
SESSION_DOMAIN=.rootdomain.com

Laravel Session with database driver keeps updating after logging out

I switched to database driver for Session and migrated the table. I've noticed that even after the logout action, the value last_activity in the table keeps getting updated after every refresh, even if the user isn't logged-in anymore.
I've tried removing it from the records of the database, but once the user refreshs at the login page, it gets inserted again.
I believe I'm doing something wrong to logout the user well. I want Laravel to stop refreshing the record of the session, as it might cause issues if every logged-out user kept accessing the database with their refreshes.
I'm logging in like this:
if (Auth::attempt($request->only('email', 'password'), ($request->remember_me === "on" ? true : false))) {
// return settings too
if(Auth::user()->active === false){
return response()->json(array('status' => 'failure', 'message' => "Your account isn't active!"),500);
}
return response()->json(
array(
'status' => 'success',
'message' => "Login is successful!"
),
200
);
}
I'm logging out like this:
public function logoutUser(Request $request){
Auth::user()->tokens()->delete();
Session::flush();
}
It's a SPA project via Sanctum.
config/session.php
'driver' => env('SESSION_DRIVER', 'database'),
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
'encrypt' => false,
'files' => storage_path('framework/sessions'),
'connection' => env('SESSION_CONNECTION', null),
'table' => 'sessions',
'store' => env('SESSION_STORE', null),
'lottery' => [2, 100],
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
'path' => '/',
'domain' => env('SESSION_DOMAIN', null),
'secure' => env('SESSION_SECURE_COOKIE'),
'http_only' => true,
'same_site' => 'lax',
The user access /login page, then they get redirected to /dashboard. Basically, /dashboard needs auth, otherwise, you don't need to be logged in.
I've tried using /dashboard by the path field and cleared the config, it didn't work.
** I've noticed that the session gets registered regardless if the user is logged or not, as long as the user visits the website, it gets registered. My understanding was that it happens after the user is logged, as it would be a hassle to insert a record whenever a guest visits.
My question shifts into the following: How can I prevent this behavior from happening? I want to limit the session saving on a specific path only, which is /dashboard, and I want to ignore the session tracking for unlogged users. The moment they logout, the session gets destroyed.

Laravel - Compatible session for different subdomains

I have one Larav app working on subd1.example.com, working properly and with this config as part or config/session.php
'driver' => env('SESSION_DRIVER', 'file')
'cookie' => 'subd1examplecom'
'path' => '/'
'domain' => env("DOMAIN", "subd1.example.com")
The thing is we have a different domain subd2.example.com with:
Different front layout
Same laravel app as dubd1
Same database as dubd1
Same storage folder as dubd1
But the subd2.example.com is not working as the session is conflicting the other one.
CAn you help on how to manage please?
Thank you

multiple session files are created on each request in laravel 5.2.*

Currently I'm working with laravel 5.2.29. On each request new session file is generated and the old file is not deleted.
config/session.php file
<?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,
'http_only' => true,
];
I put all routes inside middleware group 'web'
Route::group(['middleware' => ['web']], function () {
//Login
Route::post('login', 'User\LoginController#login');
});
Why this happens? How to solve this problem?
I have tried with changing the cookie name, previuosly in laravel 5.2.23 it works fine so I downgrade the project to laravel 5.2.23 and tried But not working.
Someone help me out to solve this.
Remove the Route::group and that should remove the duplicates. As for the old session files, it will be cleaned up after some time. Just leave it alone.
after the upgrade from 5.1 to laravel 5.4 I had a similar issue, I found that I didn't upgraded app/Http/Kernel.php correctly.
\Illuminate\Session\Middleware\StartSession::class
was declared twice in protected $middleware array and in
protected $middlewareGroups
after removing it from $middleware array it started to work correctly
$middleware applied to all routes and $middlewareGroups applied to specific groups

Laravel 5 session not persisting after user is logged in

I'm having an interesting issue with 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:
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
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.
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.
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();
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.
I solved changing
'cookie' => 'laravel_session',
to
'cookie' => 'myapp_session',
according to laravel the name of the cookie affects every driver
I'm not familiar with Laravel, but on CodeIgniter I save user session in CI's Session Class and Laravel has one too.
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.
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.
Here's a possible solution (Laravel 4, but it worths a try): http://laravel.io/forum/11-11-2014-authcheck-always-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.
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.
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.
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.
The session directory ie storage/framework/session/ is writable.
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.
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);
}
Don't forget to save like session()->save() or Session::save()
I have faced the same issues after the user logged in the session is not persistent.
So i found the solution for this.
just change one line in config/session.php file
Change in this code
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
)
To:
'cookie' => env(
'local_cookies',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
then clear the caches. it will fix the issue :)
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:
apt-get install ntp
service ntp start
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 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
You might wanna check public/index.php, see if there are codes before the Laravel codes. After I remove those codes, I can login just fine.
<?php
echo 'hello';
?>
<?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* #package Laravel
* #author Taylor Otwell <taylor#laravel.com>
*/
I seems, someone "messed" with my sites, and index.php is the main target for malicious codes
Just add session start and authenticate middleware to global middleware in kernel.php file
just check then cookie allow false
'secure' => env('SESSION_SECURE_COOKIE', false)
In my case I put it as true insted of true, then I changed its into
false
I am faced this problem when dealing with the oracle database, and by searching and debugging it is solving by change the protected $primaryKey = "name in lowercase"
public $incrementing = false;

Categories