Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

yisusvzq's avatar

Multiple authentication in Lumen

Hi everyone,

I'd like to get some help regarding the multi-auth in Lumen.

I have configured Auth based on JWT for users, but now I also need to add a separate auth for API clients.

I even have separate routes for each auth method, let's see an example:

// web.php

$router->group(
    ['middleware' => 'auth'],
    function () use ($router) {
        $router->get('/orders', 'OrderController@index');
        $router->get('/orders/{id}', 'OrderController@show');
        $router->post('/orders', 'OrderController@store');
        $router->put('/orders/{id}', 'OrderController@update');
        $router->delete('/orders/{id}', 'OrderController@destroy');
    }
);

Everything works fine here, I reach these endpoints if I include a valid Bearer token in the header, that was previously generated by JWT.

This is my auth.php:

// auth.php

    'defaults' => [
        'guard'     => 'web',
        'passwords' => 'users',
    ],

    'guards' => [
        'web' => [
            'driver'   => 'jwt',
            'provider' => 'users',
        ],
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model'  => App\Models\User::class,
        ],
    ],

And my Authenticate.php:

// Authenticate.php
    public function handle($request, Closure $next, $guard = null): mixed
    {
        if ($this->auth->guard($guard)->guest()) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $next($request);
    }

Now, I need new routes under a new middleware that will not check the Bearer token (JWT) and its expiration but will check the token from the header (X-API-TOKEN) and will validate there's an existing client in the table "clients", column "api_token". I'm adding these routes:

// web.php

$router->group(
    ['middleware' => 'client'],
    function () use ($router) {/* Orders */
        $router->get('/orders', 'OrderController@indexClient');
        $router->get('/orders/{id}', 'OrderController@showClient');
        $router->post('/orders', 'OrderController@storeClient');
    }
);

And here's my question: I can create a new middleware "client" as I declared in web.php, but I don't know what role plays here AuthServiceProvider.php. I'm not using that at all, function boot() is empty. I tried to learn how to use the "viaRequest" here but I got nothing clear.

How can I easily implement a new auth method checking the api_token? I read adding a new guard in auth.php is the best way, but I tried and didn't understand how it worked.

How would yo do it?

Thanks in advance!

0 likes
0 replies

Please or to participate in this conversation.