0

I am trying to implement a very simple authentication mechanism with Laravel 5.7, and am not sure of the best approach to take.

For the sake of reducing my issue to the most simple terms possible, let's say that I want to protect certain routes so they are viewable only by users from a specific IP address. If a user from a different IP address attempts to access a protected route, they will be redirected to an external URL.

Basically, I want to do this:

if ($_SERVER['REMOTE_ADDR'] != '123.45.67.89') {
    return Redirect::away('https://external-url.example.com/login');
}

What is the cleanest way to implement this in Laravel? I've read a lot of tutorials that explain how to create custom Auth providers, but they seem overly complicated for what I'm doing.

Can I simply create a single middleware class that implements the code above? What are some terms that I can search for via Google, to find tutorials that will help me through implementing this?

1 Answer 1

2

Middleware

<?php

namespace App\Http\Middleware;

use Closure;

class VerifyIpAddress
{
    /**
     * Check request ip address and .. 
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->ip() !== 123.123.123.123) {
            // forbidden page or smth!  
        }

        return $next($request);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works. I also had to register this middleware in app/Http/Kernel.php, by adding it to the $routeMiddleware array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.