bump.
laravel middleware order (auth sanctum)
I'm using a small middleware to ensure all requests to /api* are answered by JSON by laravel (enforcing JSON).
class ForceJsonResponse
{
public function handle($request, Closure $next)
{
//only to see if called
dd("called");
//force JSON response from API
$request->headers->set('Accept', 'application/json');
$request->headers->set('Content-Type', 'application/json');
return $next($request);
}
}
First of all I tried to use this middleware directly inside Kernel.php under $middlewareGroups like this:
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\ForceJsonResponse::class,
],
My routes file (middleware) at this moment:
Route::middleware(['auth:sanctum', 'throttle:sanctum_token_limit'])->group(function () {
//API Routes
});
I was able to see the middleware is never called when a user is unauthenticated (I expect the output to be called, even if the user is NOT authenticated) / no bearer token is present in request.
I tried to include the ForceJsonResponse middleware directly into the middleware() call of route, because so I thought I can enforce the order of the middleware are being used, so I ended up by using this inside Kernel
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
protected $routeMiddleware = [
'forceJson' => \App\Http\Middleware\ForceJsonResponse::class,
Inside my middleware() of routes I called it like:
Route::middleware(['forceJson', 'auth:sanctum', 'throttle:sanctum_token_limit'])->group(function () {
//routes...
}
This doesn't call my custom ForceJsonResponse middleware too, where did things go wrong?
@snapey just for your records :)
see https://github.com/laravel/sanctum/issues/162#issuecomment-1860443876
Solved by this post, referencing it inside the api middlewaregroups and NOT inside the constructor of class or inside the route definition fixed the problem.
Please or to participate in this conversation.