Laravel Passport CreateFreshApiToken初始登录和工作流程

时间:2019-02-09 13:12:01

标签: laravel laravel-passport

我有一个Vue CLI前端,因此我试图使用Laravel Passport来处理请求的身份验证。

https://laravel.com/docs/5.7/passport#consuming-your-api-with-javascript

我有一条执行以下(almost copy and pasted from here)的api/login路线:

public function login(){ 
  if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ 
    $user = Auth::user(); 
    $success['token'] =  $user->createToken('MyApp')->accessToken; 
    return response()->json(['user' => $user], $this->successStatus);
  } 
  else{ 
    return response()->json(['error'=>'Unauthorised'], 401); 
  } 
}

在我用AJAX请求点击它之后,用户已成功登录。

但是,如果我在Vue动作中这样做:

login({commit, dispatch}, {email, password}){
  axios.post('/api/login', {
    email, password 
  }).then( response => {
    console.log("Check login was successful", response.data);
    commit('setUser', response.data);
    axios.get("/api/user").then(response => {
      console.log("Still logged in:", response);
    });
  });

控制台显示以下内容:

Check login was successful {user: {…}}
GET http://localhost:8080/api/user 401 (Unauthorized)

Laravel文档说...

  

此Passport中间件会将laravel_token cookie附加到您的外发响应中。

我做错了什么/如何访问以后的请求laravel_token

1 个答案:

答案 0 :(得分:0)

我通过以下操作解决了这个问题。

我已经在创建if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ $user = Auth::user(); $accessToken = $user->createToken('MyApp')->accessToken; return response()->json(compact('user','accessToken'), $this->successStatus); } ,但从未发回。所以第一步:

axios.post('/api/login', {
    email, password 
  }).then( response => {
    // Send the auth token every time : )
    axios.defaults.headers.common['Authorization'] = "Bearer " + response.data.accessToken;
    commit('setUser', response.data.user);
  });

然后在我的Axios请求中:

public function store(Request $request)
    {
        $validated = $this->validateUser();
        $request_data = $validated->except(['permissions']);
        $request_data['password'] = Hash::make(123456);
        $user = User::create($request_data);
        $user->attachRole('admin');
        $user->syncPermissions($request->permissions);  
        return redirect()->route('dashboard.users.index');
    }

public function update(Request $request, User $user)
    {
        $validated = $this->validateUser($user->id);

        $request_data = $request->except(['permissions']);
        $user->update($request_data);
        $user->syncPermissions($request->permissions);
        return redirect()->route('dashboard.users.index');
    }


public function validateUser($value=null)
    {
        return request()->validate([
            'full_name'   => 'required|min:5|max:255',
            'email'       => 'required|unique:users,email,'.$value,
            'civil_num'   => 'required|unique:users,civil_num,'.$value,
            'permissions' => 'required|min:1',
        ]);
    }