Ettur
Ettur

Reputation: 809

Laravel OAuth2 Passport API, generates Token but then unable to make requests : "unauthenticated"

I have installed OAuth2 Passport to my Laravel project. I am using postman to test, I can create new user, I can login (token is generated) and logout. Once I have logged in I try to make request to an API endpoint but here I get stuck as no matter what I get 401 Unauthorized response in postman "message": "Unauthenticated."

When I make GET request to endpoint I include following headers:

Content-Type: application/json

X-Requested-With: XMLHttpRequest

Authorization: Bearer TOKENHERE

This is my routes file api.php

Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});

Route::get('trip/{id}', 'TripController@getUserTrips');
Route::get('trainroute/{id}', 'TripController@getTrainRouteInfo');
Route::get('routestops/{id}', 'TripController@getRouteStops');
Route::post('trip', 'TripController@addTrip');
Route::get('trip', 'TripController@errorTrip') -> name('test');
           

Route::group([
    'prefix' => 'auth'
], function () {
    Route::post('login', 'AuthController@login');
    Route::post('signup', 'AuthController@signup');
  
    Route::group([
      'middleware' => 'auth:api'
    ], function() {
        Route::get('logout', 'AuthController@logout');
        Route::get('user', 'AuthController@user');
    });
});

In my TripController, where are the endpoints I wish to access, I've included

public function __construct()
    {
            $this->middleware('auth');
    }

I have searched for answers and tried several things, such as editing .htaccess file and made sure to include Authorization header to GET request.

Upvotes: 2

Views: 797

Answers (1)

Ettur
Ettur

Reputation: 809

After a long long, hours long dive into this problem the answer was rather simple, in my TripController I had this

public function __construct()
    {
            $this->middleware('auth');
    }

but I'm using api routes, and then I saw login etc middleware was named 'auth:api' so I tried same and ... IT WORKED!

so this is correct

public function __construct()
    {
            $this->middleware('auth:api');
    }

Upvotes: 1

Related Questions