error status 401 error unauthenticated laravel pas

2019-08-05 05:55发布

问题:

This is my first time implementing laravel passport

This is my config/auth.php

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

and this is where my routes/api.php that are guarded by auth:api

Route::group(['middleware' => ['auth:api']], function () {
    Route::resource('users','Users\AdminUsersController')->except([
    'create', 'edit'
    ]);
});

and this is how I fetch the api

fetchUsers: async function(page_url){
     await axios.get('api/users')
     .then( response => {
          vm.users = response.data.data;
      })
     .catch( error => {
          console.log(error);
      });
 },

Im getting status 401 error unauthenticated. How can I fix this? TIA

回答1:

When a user logged in you want to pass his token.

$user = Auth::user();
return response()->json([
  'message'=>'You are logge in.',
  'token'=>$user->createToken('MyApp')->accessToken;
]);

And you want to send that token as a http header when you sending data after a user logged. Laravel get the logged user details by this token. This is the header.

'Authorization: Bearer '+token_when_logged_in

This is how headers setup in axios (I am not familiar with axios)

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  headers: {'X-Custom-Header': 'foobar'}
});