使用Laravel护照和Vuejs。尽管用户已通过身份验证,但Auth :: User()仍无法在刀片上工作

时间:2019-12-30 11:34:58

标签: php laravel vue.js laravel-passport

我正在使用Laravel护照来验证用户身份。从我的Vuex商店。我这样调度登录操作:

login({ commit}, user) {
    return new Promise((resolve, reject) => {
      let url = `/auth/login`;
      let email = user.email;
      let password = user.password;

      axios.post(url, { email, password })
      .then(response => {
        const token = response.data.token
        const user = response.data.user

        localStorage.setItem('AnimeStock.jwt', 'Bearer '+ token);
        localStorage.setItem('AnimeStock.user', JSON.stringify(user));

        axios.defaults.headers.common['Authorization'] = 'Bearer '+ token;

        commit('AUTH_SUCCESS', {token, user});

        resolve(response);
      })
      .catch(error => {
        console.log(error)
        commit('AUTH_ERROR', error.response.data.error)
        localStorage.removeItem('AnimeStock.jwt')
        localStorage.removeItem('AnimeStock.user')
        reject(error)
      })
    })
  }

这有效,并且用户已通过身份验证。接下来,我尝试像这样从vue组件中获取用户。

api.get(`/auth/user`).then(response => {
    console.log(response.data)
});

我的API路线:

Route::group(['prefix' => 'auth'], function () {
    //Auth routes
    Route::post('login', 'AuthController@login');
    Route::post('register', 'AuthController@register');

    Route::group(['middleware' => 'auth:api'], function() {
        Route::get('logout', 'AuthController@logout');
        Route::get('user', 'AuthController@user');
    });
});

它会命中我的AuthController并返回当前登录的用户。

public function user()
{
     $user = Auth::user();
     return response()->json($user);
}

当我在布局刀片文件上执行此操作时,但是工作正常,

<script>
    @auth
      window.User= {!! json_encode(Auth::user(), true) !!};
    @else
      window.User= [];
    @endauth
</script>

这也不起作用

@php
$user = Auth::user()->id
@endphp

0 个答案:

没有答案