Laravel Passport Route redirects to login page

Keith picture Keith · Feb 8, 2017 · Viewed 26.9k times · Source

I'm using Laravel 5.3 & Passport.

When using Postman to test any route I have set in api.php file it always returns the login page. Here is an example of my testing route:

Route::get('/getKey', function() {
    return 'hello';
})->middleware('client_credentials');

Postman params:

Accept application/json
Authorization Bearer <then my key>

I have set middleware to 'auth:api' per another solution I found while searching for the answer.

protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware('auth:api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }

I've tried just about every solution that has worked for others but still no luck. Any suggestions would be much appreciated.

UPDATE So I finally got something to work. I created a consumer app and created a few test functions. I was able to consume the api, with verification of token. However, hitting this Route no longer returns my login page, but instead now returns nothing. So its still not working for whatever reason.

Route::get('/user', function (Request $request) {

    return $request->user();
})->middleware('client_credentials');

Answer

madz picture madz · Mar 21, 2017

The redirection to the defined login route is occurring in the app\Exceptions\Handler.php class.

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest(route('login'));
}

The function tries to detect whether it is being called from an API (it which case it returns a 401 Unauthorized reponse with JSON message) and if not it will redirect to the login page according to the comments it

Converts an authentication exception into an unauthenticated response

To resolve the issue in postman, on the request click on the Headers tab and add:

key:   Accept
value: application/json

I'm pretty new to this so am not sure whether this is a header we should be adding when testing all API calls with Postman or just a nusience with how this laravel method is setup.

Anyway this would solve your issue with being redirected to the login page, however it's a sign your underlying authentication isn't working