rook
rook

Reputation: 1164

“Unauthenticated” when consuming own API with passport?

I have installed passport as the documentation instructed and added this line the 'web' middleware:

'web' => [
    // Other middleware...
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],

and now , Iam trying to get some data using datatable ( datatables.net ) with ajax:

api.php

Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function()
{
  Route::get('/itemsData', 'DataController@getItemsData')->name('api.getItemsData');

});

in blade:

<script>
    $(document).ready(function() {
        $('#Table').DataTable({
            "order": [],
            "processing": true,
            "serverSide": true,
            "ajax": "{{ route('api.getItemsData') }}",
            "columns": [{
                "data": "name"
            }, {
                "data": "created_at"
            }],
        });
    });
</script>

but Iam getting this as a response:

{"message":"Unauthenticated."}

Upvotes: 0

Views: 1721

Answers (2)

rook
rook

Reputation: 1164

Ok, Passport was looking for 'X-CSRF-TOKEN' which is not in the request header, so It must be added.. so, for this case:

 "ajax": {
     "url": "{{ route('api.getItemsData') }}",
     'beforeSend': function (request) {
             request.setRequestHeader("X-CSRF-TOKEN", '{{ csrf_token() }}');
     }
 },

Upvotes: 3

linktoahref
linktoahref

Reputation: 7992

You need to pass the access_token that you have obtained from Passport in request header as

$.ajaxSetup({
    headers: {
        'Authorization': 'Bearer ' + 'your access token'
    }
});

Upvotes: 1

Related Questions