Search code examples
laravelapilaravel-passport

How to add status in default response passport


I am developing and application in web as well as App. For App's API I have use Passport in laravel. Using passport i can create token and using that token I verify user for other api access. But if token in invalid then it return Error message like "Unauthorized" without any status. Can any one tell me what to do if i want to add error status like 401 with message "Unauthorized" . Where I have to change in code so that my web code is not affect. I want json response like below with 2 fields in json.

status:401 message:Unauthorized


Solution

  • You could create a new exception handler middleware to catch these requests and modify the response it returns.

    Example:

    class oAuthExceptionHandler {
        public function handle($request, Closure $next) {
            try {
                $response = $next($request);
    
                if (isset($response->exception) && $response->exception) {
                    throw $response->exception;
                }
    
                return $response;
            } catch (\Exception $e) {
                return response()->json(array(
                    'result' => 0,
                    'msg' => $e->getMessage(),
                ), 401);
            }
        }
    }
    

    Then, in your app/Http/Kernel.php, name your middleware and add it into your api group:

    protected $routeMiddleware = [
        'oauth_exception' => oAuthExceptionHandler::class,
        ...
    ];
    
    protected $middlewareGroups = [
        ...
    
        'api' => [
            'oauth_exception',
            ...
        ],
    ];