Laravel Passport How to show custom error message when invalid token is supplied

Viewed 1088

I am trying to create an API with Laravel passport, and I have to protect some routes so that only authenticated users can access these routes.

Route::post('register', [ApiAuthController::class, 'register']);
Route::post('login', [ApiAuthController::class, 'login']);
Route::middleware('auth:api')->group(function () {
    Route::post('/task', [ApiControllerTaskController::class,'store']);
});

Now hereafter login, I got an access token, and I used this access token like this. enter image description here

Everything is working fine here, but I want to show an invalid token error message when I removed the bearer token. Instead, I got this. enter image description here

3 Answers

Make sure you added the Content-type : application/json in your headers in Postman before sending your request

This worked for me, If your laravel version is >= 8.* add this code to your Handler.php witch located in App/Exceptions/Handler.php

public function render($request, Throwable $e)
{
    if ($e instanceof AuthenticationException) {
        return response()->json($e->getMessage());
    }
    return parent::render($request, $e);
}

If you need more help, leave me a commment. I hope I can help:)

//this worked for me (laravel 5.5)  App\Exceptions\Handler.php (CTRL render)
 protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson() || $request->header('Authorization')) {
    
            $response = ['status' => false, 'message' => 'Invalid token supplied'];

            return response()->json($response, 401);
        }
        return redirect()->guest(route('login'));
    }

Related