Laravel 5 Auth logout not working - php

When I use the built-in Authentication and try to log the user out at /auth/logout - it does not work as hoped. It appears to keep the user logged in. But when I clear my browser cache, I can see that is has actually logged the user out.
I don't get any errors on the page nor errors in the log file.
I am guessing that Session::flush() at the logout method would possibly solve this - but I don't know where to put it.. Can someone point me in the right direction?

For anyone that has problems solving it with the accepted solution: I started with Laravel 5.1 and updated to 5.2. The following fix worked for me:
Try changing your 'logout' route to
Route::get('auth/logout', 'Auth\AuthController#logout');
or in AuthController constructor add
public function __construct()
{
$this->middleware('guest', ['except' => ['logout', 'getLogout']]);
}
Taken from: https://stackoverflow.com/a/34667356/1275778 (also check the other answers there if you're still having problems afterwards)

Try this..
Put In following code "class AuthController extends Controller"
public function getLogout()
{
$this->auth->logout();
Session::flush();
return redirect('/');
}

I had the same problem.
The problem was actually a simple little error in the configuration of the route and controller.
You see the route actually specifies a method of getLogout and the controller exception is looking for logout.
The only thing you need to do is change the exception in the controller. No need for any additional methods. The getLogout method already exists and works perfectly.
Here is the actual code
app/Http/routes.php
Route::get('auth/logout', 'Auth\AuthController#getLogout');
app/Http/Controllers/Auth/AuthController.php
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
The _construct method should look like that:
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'getLogout']);
}

this ocurrs because the middleware is called for every route. you can add a exception to " logout route" in App\Http\Middleware\RedirectIfAuthenticated.php
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (!$request->is('/logout') && Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
}

For logout in laravel 5.6 and later version :
use in your view page:
Logout
use this in your web.php
Route::get('logout', 'Auth\LoginController#logout');

I had the same problem with updated laravel 5.2. I have used laravel's auth controller and I solved this problem using like,
/logout instead of /auth/logout same for /register and /login in instead of using /auth/register and /auth/login.

Laravel 5.2 the url is a little different ...
Use this
php artisan make:auth
This will generate the routes for auth and some templates for login e register...
Be careful to use this with existing projects, it can make changes to your code

Not enough on browsers that recover your tabs after crash (Chrome doesn't delete session cookies) . Also, after redirect a new session is created. Solution: in AuthController, as mentioned above, in getLogout, set a variable and pass it to redirect:
$data['logout'] = true;
return redirect('/')->with('data',$data);
In your home view do this:
#if(session()->has('data') && session('data')['logout'])
{{session_unset()}}
{{setcookie('laravel_session', "", -1, "/")}}
#endif
I believe Laravel redirect reinitialises Session. So after redirect, in view, reset delete cookie. Anybody can comment on this? Is this the right reason this works?

To log out a user with Laravel using the built in authentication tools, it is as simple as using Auth::logout();.
Please also check the various session settings in config/session.php if the sessions behaves unpredictably.

Solution is very very simple
in Http->Middleware->Authenticate.php change "login" in else statement to "/"
return redirect()->guest('/');
and define following route in routes.php
Route::get('/', function () {
return view('login');
});
for logout call following function:
public function getlogout(){
\Auth::logout();
return redirect('/home');
}
this is important redirect to "/home" instead of "/" that first calls $this->middleware('auth');
and then in middleware redirect to "/"

I had the same problem after upgrading to Laravel 5.3. To fix it, I noticed that the traits used in
App\Http\Controllers\Auth\AuthController
are outdated, so I changed the line
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
into
use AuthenticatesUsers;
and also the line in the constructor
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
into
$this->middleware('guest', ['except' => ['logout', 'getLogout']]);
Then the method App\Http\Controllers\Auth\AuthController#logout started to work properly.

In 5.4 this worked for me...
Logout
<form id="logout-form" action="/logout" method="POST" style="display: none;">{{ csrf_field() }}</form>

in case no any solutions is working try this
for multiple custom guards if you use auth()->logout then it wont work
just use auth('your-guard-name')->logout(); then it will work fine.

It is a quite old thread but finally I found a simple trick to log the user out from the server:
return Auth::logout();

Related

Laravel Auth Login Page Just Refreshes

I am using Laravel 5.4. I ran the make:auth command to scaffold out my auth controllers and views. I can register a new account without issue as it is showing up in my database. However when I try to login, the login page simply refreshes without any errors being thrown. In the login controller I have the redirect set to '/home' but this isn't happening. Any idea what could be causing this? I have a feeling this is because I made the required tweaks to allow users to login with a username rather than email. But I'm not sure what is causing my login not to work when everything else works fine.
Below is my login controller.
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
public function username()
{
return 'username';
}
}
Do a quick check to see if the route is being handled.
You might have to add Auth::routes(); in your web.php
Resource:
laravel 5.3 new Auth::routes()
Once you've run php artisan make:auth you need to also run the migrations with php artisan migrate have you done this?
I had this problem using Laravel 8.0 and found no helpful response over the internet... until I taught of checking the APP_URL set in my env...
Because I have other apps set up on other ports on the same localhost, I simply changed APP_URL from http://localhost to http://localhost:8003/, i.e, specifying the port this App is on.
Other steps I took that may contributes include generating new APP_KEY and refreshing my migration.
It's been many years, but, this took my 3 days to figure... I hope it helps someone.

Laravel Spark - redirect on login

I have a very simple problem. I just want to direct the user to somewhere other than '/home' after they login. This is not difficult if you can alter the spark software and retain those changes in every deployment. However, composer reinstalls everything when things are deployed and it is generally bad practice to make changes to core vendor software.
This seems like it should be a very basic and simple thing for the creators to work into the software. So, how do I do it?
I have tried ...
Altering the redirectTo and redirectPath variables in the auth controller and the password controller in my app.
Adding a login controller to my app - independent of spark - and then resetting the same variables.
Attempting to call the afterLoginRedirectTo and afterAuthRedirectTo functions in the Spark service provider. This returned an error indicating that the functions did not exist.
Not sure where to go from here.
After having the same issue I've done some digging and found a way of setting something other than home, I've changed a fair bit of stuff, but hopefully this works for you too!
TLDR
Spark::afterLoginRedirectTo('somenewplace');
Option 1
The variable used is: $afterLoginRedirectTo from vendor\laravel\spark\src\Configuration\ManagesAppOptions.php
You can set this within the SparkServiceProvider#boot method:
Spark::afterLoginRedirectTo('somenewplace');
Spark has its own LoginController \vendor\laravel\spark\src\Http\Controllers\Auth\LoginController.php
which has an authenticated method to handle the two factor auth settings:
if (Spark::usesTwoFactorAuth() && $user->uses_two_factor_auth) {
return $this->redirectForTwoFactorAuth($request, $user);
}
return redirect()->intended($this->redirectPath());
RedirectPath() is from the RedirectsUsers trait which is still in vendor and does the following:
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
redirectTo in the LoginController is set in the construct method:
$this->redirectTo = Spark::afterLoginRedirect();
Option 2
Create a new route to override the login function.
in web.php specify a new route for post login:
Route::post('/login', 'Auth\NewLoginController#login');
You can then extend the LoginController and override the authenticated method:
class LoginController extends \Laravel\Spark\Http\Controllers\Auth\LoginController
{
public function authenticated(Request $request, $user)
{
/**
* #var $user User
* Set some logic here of your own for new redirect location
*/
if ($user->last_page_accessed != null) {
$this->redirectTo = $user->last_page_accessed;
}
return parent::authenticated($request, $user);
}
}

Check the user's auth in all controllers' actions

I use Laravel 5.3 and I have the following problem.
[UPDATE]
My initial trouble was the appearance of an error when performing actions on the site when the user was not logged in the system.
This happened when the browser is started, where cached information is displayed by default on the page. Site interface displayed for logged users, and in his system was not. At the same time, producing some action, I get an error that the user is not authorized.
I also have group auth middleware for all my routes. When I reboot page of the site, the middleware is activated and redirectedme to the login page. The main problem is the browser shows the cached information.
So, in addition to middleware for routes I decided to make auth check in controllers.
[/UPDATE]
I want to check user's auth in every controller's action. Making the auth check in every controllers' action manually isn't a solution, because there are many controllers and actions.
So I decided to make it globally.
As all controllers extends Main Controller (App\Http\Controllers\Controller.php), I decided write the
auth()->check() in constructor:
function __construct()
{
if(auth()->check()) dd('success');
}
But... nothing happened((( Then I found the callAction method in BaseController which Main Controller extends and made checking here:
public function callAction($method, $parameters)
{
if(auth()->check()) dd('success');
return call_user_func_array([$this, $method], $parameters);
}
This time everything's OK, but I don't like this solution, because editing the core files isn't good.
Finally, I redeclared callAction method in Main Controller with auth checking, but I don't like this way too.
Is any solution?
You should use middleware:
Route::get('profile', ['middleware' => 'auth', 'uses' => 'UserController#showProfile']);
Or:
Route::get('profile', 'UserController#show')->middleware('auth');
Or using middleware groups:
Route::group(['middleware' => ['auth']], function () {
// Controllers here.
});
Or using controller's construct:
public function __construct()
{
$this->middleware('auth');
}
You can use auth middleware in your controller
public function __construct()
{
$this->middleware('auth');
}
check here : https://laravel.com/docs/5.3/authentication
if there is a group of routes this would be the easiest way
Route::group(['middleware' => ['auth']], function()
{
// here all of the routes that requires auth to be checked like this
Route::resource('user','UsersController');
}
another ways
function __construct()
{
$this->middleware('auth');
}
another way is specified on controller routes
Route::get('profile', [
'middleware' => 'auth',
'uses' => 'UserController#showProfile'
]);
see documentation
https://laravel.com/docs/5.0/controllers#controller-middleware

Laravel logout not working

I'm trying simple logout functionality in laravel 5.2 but don't really understand where am I wrong. It would be great is someone can help.
here's Route
Route::get('logout', 'loginController#getLogout');
loginController getLogout method:
public function getLogout()
{
//$this->auth->logout();
Session::flush();
Auth::logout();
return redirect('/');
}
link in view that uses this function:
Logout
session store code:
$request->session()->put('name', $username['name']);
AuthController constructor:
public function __construct()
{
$this->middleware('guest', ['except' => ['logout', 'getLogout']]);
}
When user clicks on the logout link, it does redirect to root page but doesn't really destroy session or logout. It isn't requiring login to view pages (which it should).
I too had the same problem and i have rectified by Method 1 and i had reference using Method 2.
Method 1:
Route::get('auth/logout', 'Auth\AuthController#logout');
Or Method 2:
or in AuthController constructor add
public function __construct()
{
$this->middleware('guest', ['except' => ['logout', 'getLogout']]);
}
Hope so this will clear up your Error. I had the same problem and i did like this alone
Session Destroy must be used like this
Session::forget('name');
$request->session()->flush(); // in your Controller
Try to change the route in routes.php with this:
Route::get('logout', 'Auth\AuthController#logout');
And for the logout route I use:
{{ url('/logout') }}
Normally this works, if you need to use a different controller for something especial, try to use the:
$request->session()->flush()
in the controller.
Following the Laravel 5.2 documentation -> https://laravel.com/docs/5.2/session.
Other approximation, try to modify the order in your controller, maybe it will work. According to the doc, Auth:logout() will clean all user auth data, then you can clean the other session data.
public function getLogout()
{
//$this->auth->logout();
Auth::logout();
Session::flush();
return redirect('/');
}

Laravel 5 Auth Logout not destroying session

I am using Laravel5 Auth system for my new project, I am able to use registration and login functions with out any problem but logout is not working as expected, however I get redirected to url specified at $redirectAfterLogout but it does not destroy session so even after hitting logout button I am able to see dashboard.
Does laravel has some bug in Auth system, please suggest, thanks
You have not provided any piece of code that you have used. However, the following code works:
public function getLogout(){
Auth::logout();
Session::flush();
return Redirect::to('/');
}
The Session::flush();clears all the existing sessions.
Using Laravel 5.2, I registered a listener, handled the logout event and called Session::flush as suggested above. Seemed to work pretty well. Hope this is helpful.
EventServiceProvider.php
protected $listen = [
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
'Illuminate\Auth\Events\Logout' => [
'App\Listeners\ClearSessionAfterUserLogout'
],
];
ClearSessionAfterUserLogout.php
public function handle(Logout $event)
{
Session::flush();
}
I had the same issue and I tried everything, but in the end I could fix it.
My problem was that when I hit on the logout button, before that I had some http requests that weren't answered yet, so even when the user was log out, later with the response of the pending requests it got logged in again. Here is an example:
Another Request | ***********************************
Logout Request | ********************
|
Time | --|------|-------------------|------|------>
t1 t2 t3 t4
So Removing those non-answered requests worked for me. I hope that this answer helps :)
By accepting the request object in a controller action (Remember to add this after the controller namespace declaration: use Auth; ):
/**
*
* Render page
*
* #route POST /user/{user_id}/logout
*
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function logout(Request $request) {
Auth::logout();
$request->session()->flush();
}
I switched to the database session driver and used the following code in my logout action
$request->session()->getHandler()->destroy($request->session()->getId());
trait AuthenticatesUsers
public function logout(Request $request)
change this
$request->session()->regenerate();
to this
$request->session()->regenerate(true);
It seems that in the
/vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
The function getLogout() is never reached, hence the logout() method never fires.
In my case, in my
/app/Http/routes.php
Iinstead of this:
Route::get('auth/logout', 'Auth\AuthController#getLogout');
I changed it to:
Route::get('auth/logout', 'Auth\AuthController#logout');
In your case you are not probably reaching the logout() method. If you are using Laravel 5 builting auth mechanism then you will run AuthenticatesAndRegistersUsers trait getLogout() method which does $this->auth->logout();
Find this code edit the method like below for debugging. If you see the string "Logging out" then you must be logged out. Ohterwise something is wrong with your routing and logout is just never executed.
/**
* Log the user out of the application.
*
* #return \Illuminate\Http\Response
*/
public function getLogout()
{
dd("Logging out");
$this->auth->logout();
return redirect('/');
}
I've been fighting with this, and I've come to a solution.
In short: The Laravel session reads and writes with middleware. It reads the stored session in at the start of the request, and writes any changes at the end of the request. If you make a redirect, then the current request never finishes, and the middleware write doesn't happen.
So, how to fix this? Depending on your implementation... you should return the redirect command rather than calling it directly.
return redirect($redirectAfterLogout)
I ran into a similar issue and it turned out using the 'file' driver for sessions somehow the server was creating files it could not modify later but there was no file permission warning. I switched to a redis implementation so I unfortunately can not say how to fix the file creation issue, but thought this might save someone some time.
You can simply override the logout method in AuthController.php
Here is code sample:
public function logout(){
Session::flush();
Auth::guard($this->getGuard())->logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}
Auth()->logout();
For the newest versions.

Categories