2

I have trouble with written route for middleware. Nothing work there. I still can see page if use another IP My task - white list. When I visited my resource with not access IP it will route on another page. I use middleware

<?php

namespace App\Http\Middleware;

use Closure;

class FilterIps
{
    const ALLOWED = [
        '1.1.1.1',
    ];

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        abort_unless(in_array($request->ip(), self::ALLOWED), 403);
        
        return $next($request);
    }
}

Add to kernel file:

protected $middlewareGroups = [
    'web' => [
        FilterIps::class,
    ],
];

My route in web. Maybe he not correct? Or maybe I have not correct solution way for my task?

Route::group(['middleware' => 'web'], function () {     
    Route::get('/demo/loginjs', function () {
        return view('auth.login');
    });
});
MisterL
  • 27
  • 4

1 Answers1

1

If you want to use it like this

Route::group(['middleware' => 'web'], function () {

you need to add your middleware to protected $routeMiddleware

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    //...
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,

    'filter' => \App\Http\Middleware\FilterIps::class,
];

then you can use it

Route::group(['middleware' => 'filter'], function () {     
    Route::get('/demo/loginjs', function () {
        return view('auth.login');
    });
});

If you want it to be on all route present in web.php, add it to the web group without calling it in web.php, it will be applied on them.

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        //...
        \Illuminate\Routing\Middleware\SubstituteBindings::class,

        \App\Http\Middleware\FilterIps::class,
    ],

    'api' => [
        'throttle:60,1',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

If you wonder why you dont need to add it in the web.php file, the answer is in \App\Providers\RouteServiceProvider::class

protected function mapWebRoutes()
{
    Route::middleware('web')
        ->namespace('App\Http\Controllers')
        ->group(base_path('routes/web.php'));
}
N69S
  • 16,110
  • 3
  • 22
  • 36