简体   繁体   中英

error status 401 error unauthenticated laravel passport

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

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'}
});

In your Kernel.php file and protected $middlewareGroups , comment or remove 'auth:api' in :

'api' => [
            'throttle:60,1',
            'bindings',
            //'auth:api',
        ],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM