okconfused
okconfused

Reputation: 3637

Passport authentication is not working in laravel 5.3

I have set-up Laravel using passport as per the documentation here:

https://laravel.com/docs/5.3/passport.

I have written one route in API route and send request http://localhost/laravel_project/public/api/user using postman but its showing me below error:

NotFoundHttpException in RouteCollection.php line 161:

I have the following route (in routes/api.php):

Route::get('/user', function (Request $request) {
    return array(
      1 => "John",
      2 => "Mary",
      3 => "Steven"
    );
})->middleware('auth:api');

but when I removed ->middleware('auth:api') line in the route it's working fine for me.

How can I fix this?

Also please tell me if I don't want to add passport authentication in my some routes how can i do this?

Upvotes: 2

Views: 2045

Answers (2)

James Dube
James Dube

Reputation: 818

I was having the same problem, it seems you have to specify the Accept header to application/json as shown by Matt Stauffer here

Some further notes:

  1. Your default Accept header is set to text/html, therefore Laravel will try redirect you to the url /login but probably you haven't done PHP artisan make:auth so it wont find the login route.
  2. When you remove the middleware it will work because you are no longer authenticating your request
  3. To authenticate some routes, just group them using Route::group and auth:api as the middleware

Upvotes: 2

Gerard Reches
Gerard Reches

Reputation: 3154

In your routes/api.php you can do this:

Route::group(['middleware' => 'auth:api'], function(){

    Route::get('/user', function (Request $request) {
        return array(
            1 => "John",
            2 => "Mary",
            3 => "Steven"
        );
    });

});

All the routes you define inside this group will have the auth:api middleware, so it will need passport authentication in order to access to it.

Outside of this group you can put your api routes that doesn't need authentication.

EDIT: In order to make sure that the route actually exists with the required middleware, run php artisan route:list.

Upvotes: 1

Related Questions