Persisting sessions across subdomains in Laravel 5 - laravel

Using 5.0
in config/session.php I have set 'domain' => '.example.com' but it is not working. I cannot persist a session on even one domain like this.
My site has many subdomains:
vancouver.example.com
newyork.example.com
etc... they are hosted on the same server and are the same Laravel app (share the same storage directory)
I login with the correct credentials, upon which the app redirects to another page on the site, and I have no session at that point. var_dump(Auth::user()) shows null even though I logged in with the correct credentials.
storage/framework/sessions shows 14 different files there, they are all for me and I cleared them out before I started testing this.
I'll attach my AuthController#postLogin method below, which works fine if session.php 'domain' => null
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if ($this->auth->attempt($credentials, $request->has('remember'))) {
Session::flash('message', 'You are now logged in.');
Session::flash('status', 'success');
if (str_contains($_SERVER['HTTP_REFERER'], '?goto=')) {
$params = explode('?', $_SERVER['HTTP_REFERER'])[1];
$target = explode('=', $params)[1];
} else {
$target = '/';
}
return redirect($target);
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}

Figured it out. Update domain => '.example.com' in session.php and clear the cookies for the site in question.

#gadss
you need to add session table like this
php artisan session:table
composer dump-autoload
php artisan migrate
and change .env to
SESSION_DRIVER=database
also modify config/session.php
'driver' => env('SESSION_DRIVER', 'database') and
'domain' => '.yourdomain.com'
after that clear your browser's cache and cookies.

You'll need to update the session configuration to persist the session in domain-wide including subdomains. Follow the steps given below.
Go to config/session.php and update the domain with prefix . as config => '.your-domain.com'.
Then clear your application cache, Open the Chrome DevTool and Go to Application > Application > Clear Storage. You'll need to clear out the previous cookies also.
run artisan command php artisan config:cache or php artisan config:clear to drop previously cached laravel application configs.
If you are using database as the session driver, You need to create a session table for that. run command php artisan session:table to generate the session table migration and then migrate it using php artisan migrate. Then perform the three steps given above.

With Laravel 8 it becomes more simplier :
Add SESSION_DOMAIN to your .env file :
SESSION_DOMAIN=.yourdomain.tld
Clear configuration cache :
php artisan config:cache
Delete your browser sessions cookies, then session become shared between all your subdomains.
In my case I used to AutoLogin user to subdomain once account is created on www. domain. Worked fine.

Have you tried storing the sessions in the database, memcached, or redis instead of in files? I had a similar situation to yours and storing sessions in the database solved the issue for me.
For some reason Laravel's session driver doesn't handle cross domain sessions correctly when using the file driver.

If someone still gets the problem with subdomain cookie. Try to change Session Cookie Name in config/session.php

If someone needs to sync session in subdomains with different laravel application sharing same database
Follow all the instructions of #Kiran Maniya
Then you have to keep same application name in order to get same session name. Or just change the cookie config in config/session.php
You can hardcode it if keeping same name is not possible.
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
)
to something like:
'cookie' => env(
'SESSION_COOKIE',
'session_sharing_application_session'
)

Related

Laravel automatically logged out with multiple users?

I'm currently developing a website with multiple users.
I tested logging in the other users in incognito and after a few seconds some of them automatically logs out.
When using only 1 user the website doesn't logs out and working fine.
I'm using
I already changed the SESSION_DRIVER in to database in the .env file but still logging out occurs. Do you know any explanation about this? Thank you.
public function grant_auth($name,$section)
{
$data_auth =
[
'name' => $name,
];
if(Auth::attempt($data_auth))
{
Session::put('section',$section);
Session::save();
return Redirect::route('dashboard');
}
else
return Redirect::to('login');
}
Im granting authentication using this code. I didn't use php artisan make:auth.
change your config/session.php
'lifetime' => 4320,
'expire_on_close' => false,
after that clear config cache
php artisan config:cache
more here: Laravel session expire time for each session

laravel 6 session restart through each request

I'm working with Laravel 6, and my session driver is file. I've faced a 419|page expired when I submit a form with post action and after tracing the codes I found out the session will restart after submission. Everything is good on local but on the server I've got this issue.
I tried with a raw Laravel project and it worked!
I've already checked directory permission, config/session.php,.env file.
.env
SESSION_DRIVER=file
SESSION_LIFETIME=120
config/session.php
'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false
Tnx for responding.
the problem is not because of CSRF token, it's session's fault. evry time a new session and new token will be started so the token thet I send from input will be checked with another token !!!
If your form is in a blade, after starting the <form>, add a csrf field by putting #csrf.
If you're sending the POST request from somewhere else (i.e. from some other domain/subdomain that is not project domain) you may want to disable CSRF check by adding it in VerifyCsrfToken.php (\app\Http\Middleware\VerifyCsrfToken.php) like this:
class VerifyCsrfToken extends BaseVerifier
{
protected $except = [
// Place your URIs here
];
}

Laravel keeps logging me out after login

I have Laravel set up. I am running multiple domains to it. Before yesterday I had one top level domain and a few sub domains. I added another TLD yesterday and everything started working weird. Specifically, when trying to log into the admin section it redirects to the home page. I have one admin but server domains coming to the site. My route group it:
Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function() {
Sometimes is actually brings me into the admin but as soon as I click on a link I get logged out and redirected to the home page. I keep seeing 401 errors in the console as well.
What would cause this?
edit
Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function() {
Route::get('/', 'AdminController#index');
Route::get('/pages', 'AdminController#pages');
Route::get('page/create', 'AdminController#createPagePage');
Route::post('createPage', 'AdminController#createPage');
Route::get('/page/edit/{page_id}', 'AdminController#editPagePage');
Route::post('editPage', 'AdminController#editPage');
});
$redirectTo = '/';
If you are using Linux, try to check the session file permissions and change them so the app can write session keys on that file and if it doesn't work, try to change the session driver to database.
how to change the session driver?
Go to your .env file and change SESSION_DRIVER=file to SESSION_DRIVER=database.
create a session migration: php artisan session:table.
composer dump-autoload.
Finally migrate (php artisan migrate).
Have you setting the SESSION_DOMAIN right?
One thing you may notice is that session isn’t saved when the user is logged-in in one store and goes to another. To fix that issue, we’ll need to add a SESSION_DOMAIN variable to our .env file, for example:
SESSION_DOMAIN=’.example.com’
That’s all, now user session will be shared across all shops/subdomains in our app.
https://medium.com/#maxkostinevich/how-to-build-multi-domain-laravel-application-e6d87d5e507b
If you are confident with the domain setup correctly. Please verify these few things.
1. Your config/session.php is correctly setup to support multiple domains.
'driver' => env('SESSION_DRIVER', 'file'), // check /storage folder writtable recursivelly.
'domain' => env('SESSION_DOMAIN', null), // verify if single domain is not given in .env or in settings.
'same_site' => null // it should not be strict if you have ajax request across these domain. I mean from javascript you may try to request to other domain.
etc...
2. Confirm, if your routes are not group under domain specific. something like:
Route::group(['domain' => 'xxx'], function($params)
{
// your routes..
});
3. If there is any hardcoded domain verification/conditions or redirection added in code.
4. Any values in .env poiting to single domain.
5. Also don't forgot to clear the cache/compiled view/routes and delete the temp files once. like generated files inside /app/bootstrap & /storage
// Clear Application Cache
php artisan cache:clear
// Clear route cache
php artisan route:cache
// Clear config cache
php artisan config:cache
// Clear compiled view files
php artisan view:clear
6. Any thirdparty package might contains the domain settings. Make sure to verify the files in your /config folder.
7. Check the url rewrite settings in .htaccess
8. Do confirm if there is any proxy settings are there or any software installed on server - very rare case.
In case still having issue, please restart the apache/nginx service once because sometimes the config changes not effected after change that might need server restart.
Hopefully it helps.

Laravel mailgun driver ignores verified domain and uses sandbox instead

I'm trying to use mailgun to send notifications to users. I have verified domain, but even though my config\services.php file looks like this:
'mailgun' => [
'domain' => 'mg.mydomain.biz',
'secret' => 'key-3223423423n423j42jklkj23l',
],
all the emails go through sandbox domain.
php artisan config:clear does not help. It is the same with development and production environment. Also I need to point out that emails come from #maydomain.biz when config\mail.php clearly states 'from' => ['address' => 'no-reply#mg.mydomain.biz', 'name' => 'Sender'],. I channged it hours ago and cleared config cache un restarted web server since.
sudo service supervisor restart solved the problem.

Laravel 4.1 session variables getting randomly forgotten

I'm using a Laravel 4.1 app on Apache, and everything is working fine on my local dev machine, but on my staging machine (which is on a shared host) users are randomly getting logged out and prompted to enter their credentials again.
The relevant settings:
app/config/session.php:
<?php
return array(
'driver' => 'file',
'lifetime' => 120,
'expire_on_close' => true,
'files' => storage_path().'/sessions',
'connection' => null,
'table' => 'sessions',
'lottery' => array(2, 100),
'cookie' => 'laravel_session',
'path' => '/',
'domain' => null,
'secure' => false,
);
using Laravel's default authentication driver
php.ini:
gc_maxlifetime=1440
gc_probability=1
gc_divisor=100
This does not seem to be the same as the issue some others have experienced here. The session file is not getting cleared by php. Just a few of the session variables are getting dropped randomly.
I tail -F'd the session file and could see when the variables are getting dropped between one request and the next. It looks like this (formatted for easier reading) before:
a:4:{
s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}
s:6:"_token";s:40:"hvuw9VWWjssSwUL2C5eVSn0qZ2g1cwVF5YCEsLG7";
s:38:"login_82e5d2c56bdd0811318f0cf078b78bfc";i:2;
s:9:"_sf2_meta";a:3:{s:1:"u";i:1399318721;s:1:"c";i:1399318011;s:1:"l";s:1:"0";}}
and after:
a:3:{
s:6:"_token";s:40:"7o3b6NhiuDKXq4ftvngUefqe6cWybX1tzPEcDaxk";
s:9:"_sf2_meta";a:3:{s:1:"u";i:1399318721;s:1:"c";i:1399318721;s:1:"l";s:1:"0";}
s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}
The login_ session is gone, which results in Laravel's Session class assuming the user is not authenticated. I am not sure why this session variable is getting dropped, though. None of Session::forget, ::clear(), ::remove() or ::invalidate() are being called on the login session variable as far as I can tell.
I also noticed that the _token variable is constant between requests until the moment when the issue arises at which point it changes, as you can see above.
Any idea what's going on here?
Switching to the database session manager seems to have solved the problem. I suspect that there was some way on my host server configuration that php was wiping out the session files.

Resources