1
votes

I am working on laravel passport package. When i revoke token and access the authenticated endpoint it throws an exception.

The logs file contain "The resource owner or authorization server denied the request". To handle is exception i created OAuth middleware and placed exception code in it as mentioned in this link: https://www.kingpabel.com/oauth2-exception-custom-error-message/

public function handle($request, Closure $next)
    {
        //return $next($request);
         try {
            $response = $next($request);
            // Was an exception thrown? If so and available catch in our middleware
            if (isset($response->exception) && $response->exception) {
                throw $response->exception;
            }
            return $response;
        } catch (OAuthException $e) {
            $data = [
//                'error' => $e->errorType,
//                'error_description' => $e->getMessage(),
                'error' => 'Custom Error',
                'error_description' => 'Custom Description',
            ];
            return \Response::json($data, $e->httpStatusCode, $e->getHttpHeaders());
        }
    }

I want to return the error in json format like:

{
    "error": "Token is invalid!"
}

I will appreciate if anyone guide me in this regard. Thanks,

3

3 Answers

2
votes

I managed to get it in this way, in the handler.php

use League\OAuth2\Server\Exception\OAuthServerException;
use Illuminate\Auth\AuthenticationException;
....

public function report(Exception $exception)
    {   
        if ($exception instanceof OAuthServerException || $exception instanceof AuthenticationException) {

            if(isset($exception->guards) && isset($exception->guards()[0]) ==='api')
            response()->json('Unauthorized', 401) ;
            else if ($exception instanceof OAuthServerException)
            response()->json('Unauthorized', 401) ;
        }

        parent::report($exception);
    }

then in order to prevent cross origin error on browser added a middleware as follows NOTE: make middleware secure in production kernal.php

protected $middleware = [
        ....
        \App\Http\Middleware\Cors::class,
    ];

cors.php

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
          ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
          ->header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With')
          ->header('Access-Control-Allow-Credentials',' true');

    }
}

1
votes

A good way to catch specific exceptions is to add your custom logic inside the render method of the App\Exceptions\Handler file.

For example, you could use:

if ( $exception instanceof OAuthException ) {
     return response(['error' => 'Token is invalid!'], 403);
}
1
votes

Now It's possible to handle OAuth exceptions with Laravel Passport 8.0+. Copy vendor/laravel/passport/src/Http/Middleware/HandleOAuthErrors.php to app/Http/Middleware/HandleOAuthErrors.php and register the binding in \App\Providers\AppServiceProvider::register() method:

$this->app->bind(HandleOAuthErrors::class, function () {
    return new \App\Http\Middleware\HandleOAuthErrors;
});