Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Passport Route redirects to login page

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');
like image 664
Keith Avatar asked Feb 08 '17 14:02

Keith


3 Answers

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

like image 175
madz Avatar answered Oct 22 '22 21:10

madz


You need to add Authorization: Bearer YOUR_TOKEN to your every request's header. Also, for latest version Laravel 5.5 or above. You need to add Accept: application/json to request header too.

like image 19
Edwin Wong Avatar answered Oct 22 '22 23:10

Edwin Wong


Add this code on Headers on postman.

key           Value
Accept        application/json
like image 15
Bijaya Kumar Oli Avatar answered Oct 22 '22 21:10

Bijaya Kumar Oli