Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize Laravel Passport response unauthenticated

Currently I have a login, register, update and delete functionality using my api made in Laravel using passport feature. Everything works fine the insertion of data and fetching the data from the database using this api. Now I wonder, how can I customize the response of the api when the token is expired. The expiration of token is working fine too. It automatically show this message

{ "message": "Unauthenticated" }

This is the code of routes where it is protected by my Oauth token where if the user did not login first then the user is not authenticated to browse the routes

 Route::middleware('auth:api')->get('/user', function (Request $request){return $request->user();});



Route::post('/timekeeping','Auth\Api\AuthController@timekeeping');

Route::post('/login','Auth\Api\AuthController@login');

 Route::middleware('auth:api')->group(function () {Route::post('/timekeeping_app','Auth\Api\AuthController@timekeeping_app');

Route::post('/logout','Auth\Api\AuthController@logout');

Route::post('/register','Auth\Api\AuthController@register');

Route::post('/show_dtr_list','Auth\Api\AuthController@show_dtr_list');

Route::post('/update','Auth\Api\AuthController@update');

Route::post('/delete','Auth\Api\AuthController@delete');

 });

Then this is how I response whenever the user successfully logged in, registered, or even logged out their accounts.

return response(['status'=>'oK','message'=>'Successful!']);

What I want is when everytime the user is using the expired token. The api should response something like this

{ "message": "Token is expired" }

not just

{ "message": "Unathenticated" }

Some threads discussed that I need to overwrite some functionalities of laravel but I don't know where and how am I going to start.

like image 919
King RG Avatar asked Jan 26 '23 07:01

King RG


1 Answers

Here's how I solved it. If you are using Laravel 5.5 or above you can override the default exception handler by editing app/Exceptions/Handler.php to add the following:

use Illuminate\Auth\AuthenticationException;

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        $json = [
            'isAuth'=>false,
            'message' => $exception->getMessage()
        ];
        return response()
            ->json($json, 401);
    }
    $guard = array_get($exception->guards(),0);
    switch ($guard) {
        default:
            $login = 'login';
            break;
    }
    return redirect()->guest(route($login));
}

In the JSON return, you can add any parameters per your requirement.

like image 165
Er Parwinder Hirkewal Avatar answered Jan 29 '23 22:01

Er Parwinder Hirkewal