Add custom middleware to Laravel Passport endpoints
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']);
In the app/Providers/AuthServiceProvider
include the Route facade by adding this use statement somewhere in the top:
use Illuminate\Support\Facades\Route;
Then on the boot()
method, put the Passport::routes() inside a Route::group() like this:
Route::group(['middleware'=>'MyFunkyCustomMiddleware'], function(){ Passport::routes(); // <-- Replace this with your own version});
Hope that helps!
If you only need to add middleware to one Passport route for example /oauth/token
, you can do it this way:
- Look up the route you need by typing
php artisan r:l
- Check the controller and method used for this route, in out example it is going to be
AccessTokenController@issueToken
- Create the controller that extends AccessTokenController, you can leave it empty
namespace App\Http\Controllers;use Illuminate\Http\Request;use Laravel\Passport\Http\Controllers\AccessTokenController;class ApiTokenController extends AccessTokenController{}
- Then create a route to that controller and method (as this controller inherits all the parent controller methods):
Route::middleware('MyMiddleware')->post('/api-token', 'ApiTokenController@issueToken');