2
votes

I'm currently building a laravel 5.4 powered page to manage users. I've done all basic pages such as home, login, register, dashboard using blade templating engine. Now I'm building the User Management page. I've successfully implemented VueJS for this particular page. All components are working perfectly.

Now the problem I'm facing now is using Axios to get logged in user data from API route. At first I'm using usual api route to get auth()->user() data but it doesn't work.

I've learned that I must use Laravel Passport to do this API operation.

These are the steps I made after that:

  1. composer require laravel/passport
  2. php artisan migrate
  3. php artisan passport:install
  4. Added the Laravel\Passport\HasApiTokens trait to your App\User model
  5. Called the Passport::routes method within the boot method of your AuthServiceProvider
  6. Set the driver option of the api authentication guard to passport
  7. Added the CreateFreshApiToken middleware to your web middleware group
  8. Edited bootstrap.js file like the following :
window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
    'X-Requested-With': 'XMLHttpRequest'
};
  1. Axios Code :
axios.post('/api/getmydata', {
    params: {
        type: 'raw'
    }
})
.then((response) => {
    console.log(response);
}).catch((error) => {
    console.log(error);
});
  1. Changed route (api.php) :
Route::group(['middleware' => 'api'], function(){
    Route::post('getmydata', 'ApiController@test');
});
  1. Added function inside ApiController :
public function test() {
    $user = Auth::user();
    return $user;
}
  1. The problem here is axios somehow return error: Unauthenticated

Is there anything wrong with my code? Or is there any other way of achieving this? Thank you

1
why you are using 'middleware' => 'api' inside api.php its automatically done by laravelNiklesh Raut
Auth::user() will not work via api.php its satelessNiklesh Raut
@user2486 - This is not true. The whole point of using passport is to authenticate API requests using a token. Thus allowing Laravel's Auth functionality to work.Joe
Do you have the meta tag in your document header which contains the token that Axios uses to send with requests? <meta name="csrf-token" content="{{ csrf_token() }}">Joe
@Joe yes I do in every page. I checked the response headers, the laravel_token and X-CSRF token is being sent to the APIRedzwan Latif

1 Answers

1
votes

Send the access token in the header of your API request:

Application Type :application/json
Authentication : Bearer [Access-Token]