error status 401 error unauthenticated laravel passport

巧了我就是萌 提交于 2019-12-13 00:55:54

问题


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


来源:https://stackoverflow.com/questions/52620707/error-status-401-error-unauthenticated-laravel-passport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!