我只允许经过身份验证的用户访问某些API路由。我使用默认的Laravel身份验证系统。默认登录后,我希望能够访问路由,但收到“未经身份验证”消息。
因此,登录后,我将重定向到使用 HomeComponent 文件的本地路由。在这里,我使用axios调用 step API路由,尝试在该路由中获取经过身份验证的用户的ID,但收到一条错误消息。我在做什么错了?
api.php
Route::middleware('auth:api')->group(function () {
Route::get('application/step', ['as' => 'application.step', 'uses' => 'ApplicationController@step']);
});
ApplicationController.php
public function step() {
print_r(auth()->user());
die('---');
// code to get authenticated user step
return json_encode(array('step' => 7));
}
LoginController.php
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
$user = User::where('email', $request->email)->firstOrFail();
if ($user && !$user->isAdmin()) {
if (Auth::attempt(['email' => $request->email, 'password' => $request->password], true)) {
$token = $user->createToken('TokenName')->token;
$token->save();
return redirect()->route('home');
}
else {
return back()->withInput($request->only('email'));
}
}
return back()->withInput($request->only('email'))->withErrors(['denied' => 'You are not allowed to access this page.']);
}
HomeComponent.vue
...
getStep() {
axios.get("/api/application/step")
.then((response) => {
this.step = response.data.step;
})
.catch((err) => {
console.log('Cannot get step', err);
});
}
答案 0 :(得分:0)
auth:api中间件仅适用于Passport。此auth:api中间件检查有效的访问令牌。
我认为您没有使用护照登录
composer require laravel/passport
在您的情况下,您只能使用auth中间件代替auth:api