User authenticating but not staying logged in Laravel 8.x - laravel

When testing my application and trying to create a new user then on form submission I am getting error 419.
If I use a helper to log in using Auth::loginUsingId(x) for an existing user then dd(auth()->user()) is successful but when I redirect to another page the user is no longer logged in. eg running the following code, you end up getting redirected to /login:
Route::get('/logInAs/{id}', function ($id) {
Auth::loginUsingId((int) $id);
dd(\auth()->user());
return redirect()->route('dashboard');
});
I would share more code but I'm not sure what would be useful at this point?
I've probably spent about seven hours trying to fix this so far. It's driving me up the wall!
The app works fine on other environments, such as staging. I've even gone so far as to re-download it from github as a fresh install (in case I was messing about in vendor directory and changed something), but that hasn't fixed it.
I get the same issue on Chrome, using different signed in users on Chrome, using incognito mode on Chrome, using Firefox, and using valet share and accessing my local version on another device, like a phone, so I don't think it is to do with browser caching.
When other devs working on the project run it locally on their machines I haven't had reports of this issue, so it seems to just me my local environment.
I've variously tried changing CACHE_DRIVER and SESSION_DRIVER in .env to no joy, but I'm beginning to lose the will to live so don't really know if I'm doing the right thing there - please help if you can!!
Edit to add more detail:
Middleware on the dashboard route:
Route::middleware(['auth:sanctum', 'verified'])->group(function(){
Route::get('/dashboard', DashboardController::class)->name('dashboard');
});
If I remove the middleware then I just get an error that user is null on dashboard.blade.php, ie the user is still not staying logged in.
A custom middleware:
class VerifyUserIsMerchant
{
public function handle(Request $request, Closure $next)
{
if ($request->user()->isMerchant()) {
return $next($request);
}
throw new AccessDeniedHttpException('You must be a merchant to access this page');
}
}
If I dd($request->user()) in this middleware it returns null.

The issue got fixed with the help of Laracasts. The full answer is here.
In short, I needed to remove the http:// protocol from SESSION_DOMAIN in .env and set it to match APP_URL.
This was the correct answer for this issue. It was deleted by a moderator. Moderator, before you delete this answer as well please can you explain why?
It provides the full answer to the issue raised in the question. I did not find this answer to this issue anywhere else (hence why it took me several days of debug to fix).
If I can know why it was deleted, I can then understand how to avoid making answers in the future that also would be deleted. Thank you.

Related

Laravel error: Sorry, the page you are looking for could not be found

I need to update a website from a colleague to just add a LDAP connexion.
I use EasyPHP devserver 17.0 with php 7.1.3 and MySQL 5.7.17.
I've read a lot of docs etc to be started and to recover the site in local as it is working actually.
Everything was working so I began to add a login form etc... but when I tried to test a link from the website, it return me the error "Sorry, the page you are looking for could not be found". So I began to search on forums I found some results about routes etc and everything I've tested didn't worked.
So, I decide to use the backup from the website as it was when I juste restore it in local(I precise link to other page and everything was working). I check the link and again, "Sorry, the page you are looking for could not be found". I decide to try another developement tool and download XAMP, exactly same error. I tried with Wamp, Laragon always same error.
In the apache conf mod_rewrite is enabled.
My laravel framework version is: 5.5.39
So my folder look like:
Laravel 5.5.39
The content of routes > web.php:
Route::get('/', function () {
return view('welcome');
})->name('welcome');
// Holidays
Route::get('/holidays/create', 'HolidayController#create')->name('holidays.create');
Route::post('/holidays', 'HolidayController#store')->name('holidays.store');
Route::get('/holidays/{holiday}/delete', 'HolidayController#destroy')->name('holidays.destroy');
Route::get('/holidays/{holiday}/edit', 'HolidayController#edit')->name('holidays.edit');
Route::post('/holidays/{holiday}', 'HolidayController#update')->name('holidays.update');
// Leave types
Route::get('/types/create', 'TypeController#create')->name('types.create');
Route::post('/types', 'TypeController#store')->name('types.store');
Route::get('/types/{type}/delete', 'TypeController#destroy')->name('types.destroy');
Route::get('/types/{type}/edit', 'TypeController#edit')->name('types.edit');
Route::post('/types/{type}', 'TypeController#update')->name('types.update');
// Users
Route::resource('users', 'UserController');
Route::get('/births', 'UserController#getAllBirths')->name('births');
// Leaves
Route::get('/calendar', 'LeaveController#index')->name('calendar');
Route::post('/leaves', 'LeaveController#store')->name('leaves.store');
Route::post('/leaves/{leave}', 'LeaveController#update')->name('leaves.update');
Route::get('/leaves/{leave}/delete', 'LeaveController#delete')->name('leaves.delete');
Route::get('/leaves', 'LeaveController#getAll')->name('leaves');
Route::get('/config', 'ConfigController#index')->name('config');
// Stats
Route::get('/statistics', 'StatsController#index')->name('stats.index');
Auth::routes();
I don't know what I could do but please ask me if you need more information to help me.
If it can help; gitLab link from the site I'm trying to restore: https://gitlab.com/balsigergil/btplan
To fix the problem I had to change the VirutalHost DocumentRoot so the root is the public directory.
DocumentRoot "C:/Users/sadm-m263733/Desktop/EasyPHP-Devserver-17/eds-www/siteBTPlan/public"

Laravel doesn't authenticate on server but does on local machine

I just uploaded a project from my local machine via FTP and it seems that the live server is working differently after trying to log in.
On the live server it's not authenticating. It gets to the __construct on AuthController.php but goes right back without errors (again, on local it works fine).
I tried adding this in Authcontroller.php:
public function postLogin(Request $request){
die();
}
And it didn't even reach it on server (it did on local).
I tried playing with the routes and instead of this:
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
I did this:
Route::post('auth/login','Auth\AuthController#postLogin');
Route::get('auth/login','Auth\AuthController#getLogin');
Didn't help on the server (local still worked fine).
I tried clearing my browser's cache, artisan cache, artisan config cache and basically anything I could find.
I tried re-uploading files from local to the server and nothing seems to work.
The most important thing here (I think) is that when I created the postLogin function it didn't even go in. That should be a huge tip if I actually knew what that meant.
The log didn't give me any errors.
Thank you #Bagus Tesa for asking to see the login file!!!
In the action of the form I added a parameter I was using for something but for some reason that's what was screwing everything up.
The important thing is that it works now...
Thanks so much!

Laravel Socialite InvalidStateException in AbstractProvider.php line 200

I'm building a web app in my local system (Ubuntu-14.04 64Bit) using laravel 5.3. I used Socialite to signin from social networks. I configured G+, Facebook, GitHug. I'm using Chromium as my default browser. Finally the problem is i'm getting
InvalidStateException in AbstractProvider.php line 200
frequently. i tried
php artisan cache:clear
php artisan config:clear
composer dump-autoload
these are helping to solve the issue temporarily, again the problem raising.
please help me in this issue..
I have the same issue and I've read a lot about this, that depend if the URL where you are at the moment of the login request has www. at the beginning or not.
Into config\services.php, if you have the redirect set as http://sitename.tld/callback/facebook the oauth works if you send the login request from sitename.tld, while if you try from www.sitename.tld you get the exception.
I haven't yet understood how to have it working with and without www at the beginning.
If the AbstractProvider.php line 200 fires the exception when the state of the user is not present means that the User cannot be created.
First check your code when you get the details from the provider(facebook, github) if you create a user and you return it.
If you have managed and logged in your app and you deleted the user from the user table remember to delete also the data from the socialite account table.
I was getting that exception because 'state' wasn't saved in session. But I was using asPopup method - Socialite::driver('facebook')->asPopup()->redirect(); so I saved session then - $request->session()->save();. So I solved this issue.
or try
session()->put('state', $request->input('state'));
$user = Socialite::driver('facebook')->user();
it works
I have same issue and solved in 3 steps;
add request on the top
use Illuminate\Http\Request;
Pass request object to function
public function handleProviderCallback(Request $request)
{
try {
$user = Socialite::driver('facebook')->user();
} catch (Exception $e) {
throw new Exception;
}
}
Clear cache.
php artisan cache:clear
I had the same error but my solution was a little different. I am posting here just in case someone else keeps hitting this post like I did for a possible answer.
I develop on Ubuntu 18.04 desktop since it is a server with a GUI. Socialite works great locally but as soon as I pushed/pulled the changes through git to the server, it quit.
I was running traces by recording what was sent to and from google. I "dd($_GET)" to get a raw dump before Socialite had a chance to get the info so I knew what was stored and ready for use. All info was there but Socialite didn't seem to "see" it. That is when I reasoned it was my apache2 header configuration interfering with the cookies/session data.
I had set header security in my apache2 configs. One of the settings was
Header always edit Set-Cookie ^(.*) "$1;HttpOnly;Secure;SameSite=Strict"
This setting was interfering with the cookie information that socialite needed. I removed that setting from my apache2 header config(by commenting out) and restarted Apache. Finally I removed all sessions in storage/framework/session/* and cleared them from my browser just to be sure. That worked for me.
After I got it working, one by one enabled and tested each of the following settings to have the framework secure what header info it can:
SESSION_SECURE_COOKIE=true
in my .env file
'http_only' => true, and
'same_site' => 'lax'(setting to "strict" did not seem to work)
in my config/session.php file.
Now it is back to testing security and tweaking things back if need be.

Laravel 5 Route Strange Behaviour

I have a Laravel site set up on a Homestead box, so I'm accessing it on sitename.app:8000. I have a route called "news" but when I try to go to sitename.app:8000/news I get oddly bounced out to sitename.app/news/.
If I change the routename to "news2" I can access the desired controller action as per normal at sitename.app:8000/news2. So somehow it's "news" itself that has become uncooperative - and I'm pretty sure that we aren't even getting as far as the NewsController, when I try to access that url.
Can anyone work out from these symptoms what might be going wrong? One "news"-related change I made at some point was to add $router->model('news', "App\News"); in the boot method of the RouteServiceProvider, but removing this doesn't seem to make the difference.
ETA: People keep asking for the routes.php file. I can literally remove everything from the file except
Route::get('news', function() {
return "hello world";
});
Route::get('news2', function() {
return "hello world";
});
and /news2 will work but /news will bounce me out. So I remain pretty convinced that the problem is somewhere deeper than routes.php...
I finally worked out what boneheaded action of mine had been causing this behaviour!
I had created a folder in /public named "news"... i.e. with the same name as an important route. Not sure exactly what havoc this was wreaking behind the scenes for Laravel every time a request for /news was being made, but one can assume it was nothing good.
Advice for anyone tearing their hair out over a route that "mysteriously doesn't work" - check your public folder for possible collisions!
This is a known issue Larvel missing port
The easiest way to solve this problem is to go to public/index.php and set the SERVER_PORT value.
$_SERVER['SERVER_PORT'] = 8000;
Don't forget to set the base url in the config if you are using links on website, the url generator uses the base-url defined in the config.
Last option is to change the vm portfoward in VagrantFile to point to port 80 and use port 80 for your app.

Sentry on Laravel 4 with MAMP

I'm using Laravel on MAMP PRO (PHP 5.4). Both are vanilla install and I got Laravel working okay.
Next, Installed Sentry.
Inside of a login function on controller:
$user = Sentry::authenticate($credentials, false); // this works. I can see the $user
But then upon an immediate redirect I use a filter:
Route::filter('auth.admin', function()
{
var_dump(Sentry::check()); // ** this gives me a bool(false);
die();
if ( ! Sentry::check())
{
return Redirect::route('admin.login');
}
});
So, I'm assuming that maybe there is a cookie that is not being set?
Solved...
For anyone else with this issue, this is a summary of the most common solutions on the Internet as well as how I solved my issue. I'm on MAMP/OSX, but this apparently made zero difference as I literally put up a vagrant/virtualbox and still had the same issue.
** Set 'domain' => 'yourdomain.com' in your config/session.php. EVEN IF YOU ARE ON A SUB DOMAIN like a.b.c.yourdomain.com, use ONLY the root domain (yourdomain.com) in your 'domain' variable as I just wrote it. ** This was my issue.
Make sure your session storage folder has write permissions.
Make sure you have a >0 lifetime in your session.php
Make sure you don't have whitespaces after any closing PHP which could cause the application not to shut down properly.
Try Switching between database sessions and file sessions.
As a last resort, try upgrade to 4.2, if possible. 4.1 had a known issue (as referenced in google).
Your issue is may no be with Laravel OR Sentry. It's probably a file or configuration issue as illustrated above. I pulled my hair out tracking this from Sentry to Laravel to Cookies to Session to Blah... Only to realize that it was finally a cookie issue which was caused by me not setting my ROOT domain (I was using the full

Resources