Search code examples
laravellumen

How to use the auth:api middleware for all Lumen routes?


We have a Lumen installation with the Tymon Jwt -package and it’s working fine when we implement the middleware in the routes file, by using “auth:api” as the middleware name.

However we would like to add that middleware to all routes automatically and only whitelist a couple of routes to skip it. How is it done? Other global middlewares are installed in bootstrap/app.php but we can’t find the correct class to call if we want to use the auth:api -middleware.

I guess it’s quite simple but can’t find it.


Solution

  • To apply it to all routes, use a global middleware:

    If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the call to the $app->middleware() method in your bootstrap/app.php file:

    $app->middleware([
       App\Http\Middleware\OldMiddleware::class
    ]);
    

    tymon/jwt-auth provides several possible Tymon\JWTAuth\Http\Middleware middleware classes for your use. Pick the most appropriate to your scenario.

    (Your middleware could exempt certain routes internally, in this scenario, probably using something like Request::is('foo/*')).

    To apply it to most (but not all) routes, put the relevant routes in a route group:

    $router->group(['middleware' => 'auth:api'], function () use ($router) {
        // most of your routes go here
    });
    
    // the handful of non-auth routes go here