prevent back button after logout laravel

By : PHPErrorCode October 16, 2017 257 Views laravel

Today, I noticed that even after logout I can go to the page in laravel web application, which is not right because this is a securite issue. Usually this problem is found in many larval web applications. If you get this issue, you are right place.

Use laravel middleware to stop this problem, For which you have to create a new laval middleware. In this post, we have created a PreventBackHistory name middleware, which explain how to prevent the button after logout.

So, in this post, I will show you step by step on how to prevent the button after logout in laravel web application, only you have to follow and create a new middleware.

Step :1 Create new middleware

First we will create a new middleware named PreventBackHistory using the following command

php artisan make:middleware PreventBackHistory

Step :2 Middleware Configuration

Now Go to app/Http/Middleware/PreventBackHistory.php. Then open PreventBackHistory.php file and add the following four lines to the handle function.

header("Cache-Control: post-check=0, pre-check=0", false);
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header('Content-Type: text/html');
header("Pragma: no-cache");

PreventBackHistory.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)
    {

        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
        header('Content-Type: text/html');
        header("Pragma: no-cache");
        
        return $next($request);
    }
}

Step :3 Add Register Middleware

Now, Go to app/Http/Middleware/Kernel.php. Then open Kernel.php file and add the following line

protected $routeMiddleware = [
	//-------

	'prevent-back-history' => \App\Http\Middleware\PreventBackHistory::class,

	//-------

];

Step :4 Use Middleware In Route

There are two different ways for the routing home and backend authentication

home authentication(Frunted authentication)

Route::group(['middleware' => 'prevent-back-history'],function(){
	Auth::routes();
	Route::get('/home', 'HomeController@index');
});

admin authentication(Backend authentication)

Route::group(['middleware' => 'prevent-back-history'], function () {
	Route::group(['prefix' => 'admin','middleware' => 'adminauth'],function(){
		Route::get('/home', 'HomeController@index');
	});
});

I hope you have found this post useful,

thanks....