1

I am trying to implement a very simple authentication mechanism with Laravel.

I need to protect certain routes so they are viewable from a specific IP address.

I want to do this:

if ($_SERVER['REMOTE_ADDR'] != '123.45.67.89') {
    return Redirect::away('some url');
}

How can I implement this with a guard?

idan
  • 43
  • 6
  • Read [the docs](https://laravel.com/docs/master/authentication#adding-custom-guards), implement your guard, ask again with any code you have that has errors/warnings/doesn't work as expected – brombeer Jan 08 '20 at 14:07

1 Answers1

1

You can achieve this by using middleware as it's used for what you're trying to do.

Create a new middleware by doing php artisan make:middleware SimpleGuardMiddleware. It will be created in app\Http\Middleware\SimpleGuardMiddleware.php.

Then, in the file you can write something like this:

public function handle($request, Closure $next)
{
    if ($request->ip() != '123.45.67.89') {
        return Redirect::away('some url');
    }
    return $next($request);
}

And then, go to app\Http\Kernel.php, make sure to add this to your protected $routeMiddleware array.

protected $routeMiddleware = [
    //.. your previous files ...
    'myguard' => SimpleGuardMiddleware.php::class,
];

And then in your route file, you can do something like

Route::group(['middleware' => 'auth'], function() {
    // your routes here...
}
Taylor
  • 2,981
  • 2
  • 29
  • 70
  • Thanks, Taylor. I already implemented this with middleware. Can I implement this with a guard? – idan Jan 08 '20 at 14:24