Search code examples
laraveloauthlaravel-5.4laravel-passport

Laravel Call a middleware if another middleware fails


So I have been using Passport to handle any OAuth requests which works perfectly. However there are some scenarios where I do not need a user instance to request and API endpoint. Static lists etc. I have created a middleware for that and it works fine. And finally there are scenarios when pulling things like lists where i want to give developers the freedom to either use the Token or OAuth to post to those endpoints. And struggling on how to do that...

Anyone have any insights? I am thinking I could always call the Token middleware and then from the token middleware call the normal passport OAuth? Not really sure how i would go about doing that though.

Chaining would not work in this scenario because if one fails it would boot them out, where I want it to check for a token IF it does not exist THEN check OAuth token and follow normal behavior after that.

Route::group(['middleware' => 'token:auth:api',

Not seeing anywhere in the docs on how to do this. But maybe I am missing something.

Cheers

Citti


Solution

  • You can achieve this by making another middleware. In that middleware first you call the token middleware, if that fails then call the passport OAuth middleware. I have done to authenticate token using Tymon JWT, if that fails will authenticate using Laravel Passport OAuth. Following is the handle() function of the middleware

    public function handle($request, Closure $next)
    {
        try {
            return app(\Tymon\JWTAuth\Http\Middleware\Authenticate::class)->handle($request, function ($request) use ($next) {         //JWT middleware
    
                return $next($request);
            });
        } catch (\Exception $exception) {
    
            if ($exception instanceof UnauthorizedHttpException) {
                return app(\Laravel\Passport\Http\Middleware\CheckClientCredentials::class)->handle($request, function ($request) use ($next) {
                    return $next($request);
                });
            }
            throw $exception;
        }
    
    }