Prevent Browser's Back Button Login After Logout in Laravel 5
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.
When the user clicks the back button they're not actually logged in, its just the browser rendering what it has cached from previous page views. The user won't be able to navigate or interact with anything that requires them to be logged in because, to your application on the server, they're not authenticated.
When the user clicks the back button you have no control over that as it doesn't make a request to the server.
Using the back button, the only content they'll be able to view is that what they have already visited whilst logged in. If they try to access anything new, they'll make a new request to your application, your middleware will trigger and redirect them to the login page.
I guess if you really wanted to stop this behavior you could use some JavaScript and such to send an ajax request and check if the user is logged in that way, but quite useless from a security point of view.
Step 1 : create one middleware using following command:
php artisan make:middleware PreventBackHistory
Step 2:
replace content of PreventBackHistory.php with following content:
<?php
namespace App\Http\Middleware;
use Closure;
class PreventBackHistory
{
/**
* 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','no-cache, no-store, max-age=0, must-revalidate')
->header('Pragma','no-cache')
->header('Expires','Sun, 02 Jan 1990 00:00:00 GMT');
}
}
step 3: register middleware in kernal.php
'preventBackHistory' => \App\Http\Middleware\PreventBackHistory::class,
And good to go :)