isarantoglou's avatar

Custom API token verification middleware question

Hello,

I am building an API for an application that is not build with laravel. I tried laravel sanctum but I think its abit too complicated to integrate, since the application is not using any conventions at all and I am not sure how to do it.

So, I have made a middleware that checks the token. My first question, is this a good approach or a custom gate is better?

My second question, can I have access to the User model at my route without needing to re-query it? My middleware is this:

  public function handle(Request $request, Closure $next)
    {

        if (!$request->hasHeader('Authorization')) {
            abort(401, 'Unauthorized');
        }

        $user = User::where('api_key', explode(' ', $request->header('Authorization'))[1])->first();

        if (!$user) {
            abort(401, 'Unauthorized');
        }


        return $next($request);
    }

Note the header is "Authorization: Token 106665f4-87c2-4a79-bb5f-279f4b8973bd".

My route/api.php file is:

Route::get('/', function () {

    return 'hello world';
})->middleware('apikey');

Where apikey is the middleware.

So, since during the middleware I did query and found the user, can I somehow pass it to the route so I can then pass it to a controller without doing a SQL query again?

Thank you, Ilias

0 likes
2 replies
bobbybouwmann's avatar
Level 88

To make a middleware work with a user and keep it available you should be using a custom auth guard. Laravel will then try to find the user and log that user in. In your case, that would just be setting the user to the request and session.

Documentation: https://laravel.com/docs/8.x/authentication#adding-custom-guards

Above is the official way, then you can also reuse the existing auth middleware. Then you also have tools available like auth()->user() and so on.

Another solution is logging in the user by using the facade.

Auth::login($user);

Note that this will set the authenticated user on the default auth middleware. This means the user is also logged in on all other routes that are used in your application with that middleware. I don't think you want this approach

Finally., it's not that bad to retrieve the user twice. It's really a micro-optimization if you're only looking into speed improvements.

2 likes
isarantoglou's avatar

@bobbybouwmann

The laravel application will be only for the api part of the original application, nothing else so I think I can just login the user. If I encounter any problem I will just requery the user, as you said its not that big of a deal :)

Thank you.

Please or to participate in this conversation.