Bypass Protected API Routes in Laravel

It’s been a while since I have written any post. Several projects are in queue and waiting for their completion. Recently, in one of the project We came across a problem in which we had to make an api route accessible to both guest and authenticated user and that’s where the problem started.

Laravel’s default nature is to block the user from accessing the route if it is protected using the auth:api guard. Therefore, we looked for different solutions on the internet but couldn’t find any of use that also prevented the duplication of code.

Duplicate code is a computer programming term for a sequence of source code that occurs more than once, either within a program or across different programs owned or maintained by the same entity.

Duplication of code is bad, Trust me. Thinking for an idle solution to this problem We thought to refactor it and solve it via Middleware.

Middleware can be explained as a bridge layer between the two services.

Middleware To The Rescue

Laravel makes heavy use of middlewares. If you have ever gone through the framework You’d have noticed that the Request and Response passes through several Middleware calls. And Authenticate middleware located inside App\Http\Middleware directory is one of those whose only soul work is to authenticate the user based on the guard used in the application.

Thus, we planned in utilizing the capability of this middleware to create one for ourselves. That will check if the authorization token in Request assuming that the authenticated user is trying to make a call to the api and authenticating it if it exists and if not, then we continue as a guest user anyways.

For it, we created GuestBypassProtectedRoute.php file inside the App\Http\Middleware directory with the code below.

GuestBypassProtectedRoute.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

/**
 * Class GuestBypassProtectedRoute
 * 
 * @author Abhishek Prakash <[email protected]>
 * @package App\Http\Middleware
 */
class GuestBypassProtectedRoute
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // The route should be accessible for both authenticated and
        // guest users.
        if ($request->hasHeader('authorization')) {
            return app(Authenticate::class)->handle(
                $request,
                function ($request) use ($next) {
                    return $next($request);
                },
                'api'
            );
        }

        return $next($request);
    }
}

The code above regenerates the Authenticate middleware from the Service Container of Laravel and proceeds with the authentication of the user if the authorization token exists in the Request header. Otherwise, we continue as the Guest user.

To use the GuestBypassProtectedRoute middleware in your application you just need to pass it as a middleware to the routes. Please make sure not to use auth:api middleware in conjunction to this for the same route.

api.php

<?php

use App\Http\Middleware\GuestBypassProtectedRoute;

Route::get('/route-name', '[email protected]')->middleware(GuestBypassProtectedRoute::class);

That’s it for today. If you’re new to programming then you might want to read You don’t understand floating points, A Deal with an Array or other posts related to the content shown below.

Finally! Thanks for reading. Feel free to correct me and share your reading experience in the comments below.