Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

php - 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');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The redirection to the defined login route is occurring in the appExceptionsHandler.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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...