Search code examples
phplaravelhttp-status-codes

Laravel Passport: Wrong token JSON response


I am using Laravel 5.7 + Passport 7.2.

My API route is as follows

// namespace "App\Http\Controllers\Admin"
Route::namespace('Admin\Api')->group(function () {

    // test route
    Route::get('test', function(){
        Return 'hello test';
    })->name('login');

    // unauthorized routes
    Route::post('authorizations', 'Auth\AuthorizationsController@store');

    // authorization routes
    Route::middleware(['auth:api'])->group(function () {

        // User controller
        Route::namespace('Users')->group(function () {
            // get user detail
            Route::get('user', 'UserController@me');
        });

        // Rbac controller
        Route::namespace('Rbac')->group(function () {
            // get tree menu list
            Route::get('menu/select', 'MenuController@select');
        });

    });
});

When I tried to request /api/user with a wrong or empty token, I got a redirect. However, in the case of pure API, errors such as 401 should be reported: TOKEN error, not 302.

How to solve this situation?


Solution

  • If you doesn't provide valid token in protected route laravel recognize as a Unauthorized and if you request it without define Accept header it will redirect to login page, if you define Accept headers to be json it will response 401 status with Unauthenticated message.

    So the solution it add Accept:application/json in your request headers.

    example with axios (javascript)

    axios({
      method: "GET",
      url: "api/user",
      headers: { Accept: "application/json" }
    });