Add custom middleware to Laravel Passport endpoints

fatuous.logic picture fatuous.logic · Aug 4, 2017 · Viewed 7.7k times · Source

I have a standard Laravel Passport setup on 5.4 - it all works fine and is generating tokens.

I protect my API routes using the auth:api middleware as well as a custom middleware that checks that specific headers in a request are present and valid before any requests are handled. This middleware works fine for the API routes group.

Is there a way to wrap the Passport routes generated by laravel '.../oauth/token' in this middleware as well?

Currently I have set up the routes in my AuthServiceProvider.php boot() method:

public function boot()
{
    $this->registerPolicies();

    // Passport/OAuth
    Passport::routes(function ($router) {
      $router->forAccessTokens();
      $router->forTransientTokens();
    });

    Passport::tokensExpireIn(Carbon::now()->addDays(7));

    Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
}

The end goal is that the oauth endpoints will return an error if the headers are not present.

Answer

rdehnhardt picture rdehnhardt · Aug 23, 2018

You can try this: Go to app/Providers/AuthServiceProvider and look for the function boot(). In this function you will see a line for registering routes for Passport. The default code is Passport::routes(). This routes() method accepts an options array as second argument. You can use it to set middlewares for Passport routes.

Passport::routes(null, ['middleware' => 'api']);