Prevent Direct Access to Pages from URL in Laravel

In this Laravel tutorial, we’ll explore the Prevent Direct Access to Pages from URL. We’ll discuss the reasons behind restricting direct access, the benefits it provides, and provide practical examples along with detailed step-by-step instructions. Learn how to add restrictions to specific pages and safeguard your Laravel application from unauthorized access. Let’s get started with this comprehensive guide.

However, if you’re creating a new page and want to restrict direct access, you’ll need to implement some code. By doing so, you can redirect users to alternative pages, such as a 404 error page or the homepage, based on your preferences. In this tutorial, we’ll walk through the process of preventing direct access to specific pages in Laravel.

Let’s get started with securing your application’s sensitive components.

Step 1: Creating a New Laravel Project

To begin, you need to create a new Laravel project. Follow these steps:

  1. Open your terminal or command prompt.
  2. Navigate to the directory where you want to create your Laravel project.
  3. Run the following command to create a new Laravel project:
composer create-project --prefer-dist laravel/laravel project-name

Wait for Composer to install the necessary dependencies and set up the project.

Once the command completes, you will have a fresh Laravel project set up and ready for further configuration and development.

Step 2: Creating a Middleware

To prevent direct access to specific pages in Laravel, you can create a middleware. Middleware acts as a filter for incoming HTTP requests, allowing you to apply certain rules or restrictions before the request reaches the intended route. Here’s how you can create a middleware:

Open your terminal or command prompt.

Navigate to your Laravel project directory.

Run the following command to create a new middleware:

php artisan make:middleware PreventDirectAccess

This command will generate a new middleware file named “PreventDirectAccess.php” in the “app/Http/Middleware” directory of your Laravel project.

Open the generated “PreventDirectAccess.php” file in a text editor.

Inside the middleware’s handle method, add the following code to redirect users if they try to directly access specific pages:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class PreventDirectAccess
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        return redirect('404');//redirect to 404 error pages
//return redirect('/');redirect home page
        // abort(403, 'Unauthorized access.'); // Show a 403 Forbidden error message

    }
}

In the provided example, the middleware always redirects the user to the 404 error page by calling redirect(‘404’). You can modify this to redirect to a different page or URL, such as ‘/’ for the home page.

Uncommenting the abort(403, ‘Unauthorized access.’); line would instead display a 403 Forbidden error message when accessing the restricted pages.

If you want to restrict access to a specific user or group of users, you can modify the middleware code to include the necessary logic. Here’s an example of how you can do it:

For specific user:

// Check if the current user is authorized to access the page
    if ($request->user()->id !== 1) {
        abort(403, 'Unauthorized access.'); // Show a 403 Forbidden error message
    }

For allowing access only when the request does not have a referrer:

if (!$request->headers->has('referer')) {
    return redirect('/');
}

For allowing access only when the request is not an AJAX request:

if (!$request->ajax()) {
    return redirect('/');
}

For allowing access only for authenticated users:

if (!Auth::check()) {
    return redirect('/');
}

For allowing access based on a specific condition or variable:

if (!$condition) {
    return redirect('/');
}

You can customize the condition based on your specific requirements. The idea is to check whether the condition for allowing direct access is met. If the condition is not met, you can redirect the user to a different page or perform any other action you deem appropriate.

Step:3 register your custom middleware

Navigate to the app\Http\Kernel.php directory.

Inside the Kernel class, you will find various properties and methods related to middleware, such as protected $middleware and protected $routeMiddleware.

The $middleware property contains the global middleware that applies to all HTTP requests. You can add your custom middleware to this property if you want it to be applied to all routes.

The $routeMiddleware property contains an array of named middleware, where you can register your custom middleware with a unique key. For example, you can add

 protected $routeMiddleware = [
        // other middleware entries
        'prevent.direct.access' => \App\Http\Middleware\PreventDirectAccess::class,
    ];

Save the changes to the Kernel.php file.

Step: 4 go to web.php

Navigate to the routes\web.php directory. By default, you will find a file named web.php in this directory.

Open the web.php file.

Inside the web.php file, you can define your application’s routes using the Laravel routing syntax. This file is specifically used for defining routes that handle web requests.

You can define routes for various HTTP methods such as GET, POST, PUT, PATCH, and DELETE.

To apply the PreventDirectAccess middleware to a route, you can use the middleware method on a route definition. For example:

Route::get('/restricted-view-page', [MyController:class, 'RestrictedPage'])->name('restricted-view-page')->middleware('prevent.direct.access');


Step: 5 your Controller page

for example MyController.php

Navigate to the app\Http\Controllers\MyController.php directory.

    public function RestrictedPage()
{
    return view('layout.restricted-view-page');
}

Step: 6 To check if the page is protected from direct access

Start your Laravel development server by running the php artisan serve command

Open your web browser and enter the URL for the page you want to test. For example, if the page URL is http://localhost:8000/restricted-view-page, enter that URL in the browser’s address bar.

Press Enter or click Go to load the page.

If the page is successfully redirected to the desired location, such as the 404 error page or the homepage, then it means the direct access to the page is restricted.

If the page is still accessible and displayed, then you may need to review your middleware and controller logic to ensure it is properly implemented.

Leave a Reply