Prevent Browser's Back Button Login After Logout in Laravel 5

Tartar picture Tartar · May 8, 2015 · Viewed 36.7k times · Source

I am new to Laravel 5 and trying to make a simple authentication page. My problem is i can logout properly after i click to logout link but if i click to back button of the browser, still able to see the content of the page which actually should not be seen with respect to my auth middleware process. I read i can prevent this by disabling caching but don't think it is the best way to do this so how can i make this in a better way ? Simply my logout route is

Route::get('logout', array('uses' => 'LoginController@logout'));

Logout function is:

public function logout() {
        Auth::logout(); // logout user
        Session::flush();
        Redirect::back();
        return Redirect::to('pages/login'); //redirect back to login
}

Answer

RaZik picture RaZik · Feb 5, 2017

Create a middleware using artisan:

php artisan make:middleware RevalidateBackHistory

Within RevalidateBackHistory middleware, we set the header to no-cache and revalidate:

<?php
namespace App\Http\Middleware;
use Closure;
class RevalidateBackHistory
{
    /**
    * Handle an incoming request.
    *
    * @param \Illuminate\Http\Request $request
    * @param \Closure $next
    * @return mixed
    */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        return $response->header('Cache-Control','nocache, no-store, max-age=0, must-revalidate')
            ->header('Pragma','no-cache')
            ->header('Expires','Fri, 01 Jan 1990 00:00:00 GMT');
    }
}

Update the application’s route middleware in Kernel.php:

protected $routeMiddleware = [
    .
    .
    'revalidate' => \App\Http\Middleware\RevalidateBackHistory::class,
    .
    .
];

And that’s all! So basically you just need to call revalidate middleware for routes which require user authentication.