Anindit Karmakar
Anindit Karmakar

Reputation: 835

Laravel 5 global middleware not working

I have a route group in my routes.php file with the middleware specified like so:

Route::group(['prefix' => 'api', 'middleware' => 'api'], function() {
    Route::post('oauth/access_token', function() {
        return Response::json(Authorizer::issueAccessToken());
    });
}

I am using the Lucadegasperi Oauth2 Server addon. For its setup, I had to enter the following LucaDegasperi item in the $middleware array of the Kernel.php file (Kernel class):

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \LucaDegasperi\OAuth2Server\Middleware\OAuthExceptionHandlerMiddleware::class,
    ];

The $middlewareGroups array of the same class is as follows:

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],

        'api' => [
            'throttle:60,1',
        ],
    ];

What the OAuthExceptionHandlerMiddleware does is that it formats exceptions to JSON responses. Now when I apply the 'middleware' => 'api' in the route group as shown, the global middlewares dont work. I can say this because the HTML error page shows when exceptions occur. However, when I omit the 'middleware' => 'api' in the route group, the global middlewares work and I get JSON responses for the errors.

How do I get past this?

Upvotes: 0

Views: 1178

Answers (2)

Matt
Matt

Reputation: 2420

The reason for this is due to changes with how Laravel handles exceptions in Middleware from 5.2.7 onwards, as documented in this ticket I raised. To fix this you need to alter your Exception handler (as explained in the issue) or await the latest patch from the package.

I've commmitted a fix to the repository which fixes the issue of the changes made to Laravel 5.2, however this has not yet been merged.

Upvotes: 1

soutoner
soutoner

Reputation: 559

Did you remember to add Authorizer to aliases array?

'Authorizer' => LucaDegasperi\OAuth2Server\Facades\Authorizer::class,

Because you're using it in:

Route::post('oauth/access_token', function() {
    return Response::json(Authorizer::issueAccessToken());
});

Upvotes: 0

Related Questions