Laravel automatically logged out with multiple users? - laravel

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

Related

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 5.7 - Spark API authentication session issues

Just going to preface this question by saying that I'm diving back into Laravel after a while of not using it, it appears there are a lot of changes, and the current project in question is using A LOT of the baked in "Laravel Ecosystem"... so I could be missing some context here.
The issue : After upgrading from Laravel 5.6 to 5.7, auth-guarded API routes are busting because of session expiry, even immediately after logging in (prompting logout).
The configuration :
/config/auth.php
'guards' => ['api' => ['driver' => 'spark']]
/routes/api.php
Route::group([
'middleware' => 'auth:api'
], function () {
// Routes in here are busting
}
/app/Providers/SparkServiceProvider.php
protected $usesApi = true; // yup
Additional info :
The site uses the Socialite plugin for managing user authentication
There are indeed spark_token's in the request
Vue client making the calls, getting status 401 Unauthorized on the next page load after successfully authenticating via login form
It was working perfectly fine before upgrading from Laravel 5.6 to 5.7
Any ideas? I've poured through the Laravel 5.7 release notes / upgrade guide, not finding any relevant info.
Found a solution that worked for me:
Add to app/Http/Middleware/EncryptCookies.php
/**
* Indicates if cookies should be serialized.
* #var bool
*/
protected static $serialize = false;
Then clear cookies from your browser, and retry logging in.

Persisting sessions across subdomains in Laravel 5

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'
)

Laravel 4: Session is not working in server

session::set and session::get is not working in laravel
Session is working in local machine. But when I test in live server, it is not working.
Scenario: While logging into an application Auth::attempt returns true. But again it redirected to login page. This is an exact issue.
Auth::check method return true under the auth::attempt condition.
But in login page and filter.php, Auth::check method return false.
I don't know why :(
I tested it with a laravel session variable. I assigned a value in a session variable and redirected the page to another page where I have echoed the session. It return empty.
Additional Detail: It does not retain the session flash message in server. It is working in local.
Please advice.
If your session driver is file, then make sure your (storage) path is writable by PHP. Look for this in your session.php file:
'driver' => 'file',
....
'files' => storage_path().'/sessions',

Resources