【问题标题】:Allow only authenticated users to access API routes仅允许经过身份验证的用户访问 API 路由
【发布时间】:2020-01-01 12:37:45
【问题描述】:

我想只允许经过身份验证的用户访问某些 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);
         });
} 

【问题讨论】:

    标签: laravel vue.js laravel-5 laravel-passport


    【解决方案1】:

    auth:api 中间件仅适用于 Passport。这个 auth:api 中间件检查有效的访问令牌。

    而且我认为您没有使用护照登录

     composer require laravel/passport
    

    在您的情况下,您只能使用 auth 中间件而不是 auth:api

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-15
      • 2017-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多