简体   繁体   English

在 API 路由中使用 Auth facade (Laravel 8)

[英]Use Auth facade in API routes (Laravel 8)

I am looking to use Auth::user() in the CompanyController sitting in the api.php route file in Laravel 8 .我希望在位于Laravel 8中的api.php路由文件中的CompanyController中使用Auth::user() Like喜欢

Route::get('team', [CompanyController::class, 'index']);

But if I do so, I won't be able to access Auth in the following code in the CompanyController file.但是如果我这样做,我将无法在CompanyController文件中的以下代码中访问 Auth。

use Illuminate\Support\Facades\Auth;

public function index(Request $request)
    {

        /**
         * Role 1 => admin, 2 => hr, 3=> member
         */

        if (Auth::user()->role <= 2) {

            return ['company' => Auth::user()->company, 'team' => Auth::user()->company->users];
        }
    }

So what I have done now to achieve what I need is prefix api to the routes sitting in the web.php route file instead.所以我现在为实现我需要做的是将前缀 api 改为位于web.php路由文件中的路由。

Route::prefix('api')->group(function () {
    Route::get('team', [CompanyController::class, 'index']);
}

After googling around, I am more or less aware that Laravel Sanctum may solve the issue, and it's happened because of the Token driver used in the Api routes.谷歌搜索后,我或多或少意识到 Laravel Sanctum 可能会解决这个问题,这是因为 Api 路由中使用的 Token 驱动程序。 But I'm wondering if there is any easy alternative solution for this.但我想知道是否有任何简单的替代解决方案。 It looks like it would take a while to customise the login page with Sanctum.看起来用 Sanctum 自定义登录页面需要一段时间。

What I want is still to take advantage of the initial login page set up with the Breeze starter kit.我想要的仍然是利用使用 Breeze 入门工具包设置的初始登录页面。 At the same time, after the user logs in, they can get access to Auth.同时,用户登录后,可以获得Auth的访问权限。

if (Auth::user()->role <= 2) {

Here you assume that the user is authenticated and you need to put this route with the authentication middleware.这里假设用户已通过身份验证,并且需要将此路由与身份验证中间件放在一起。 For example:例如:

Route::get('team', [CompanyController::class, 'index'])->middleware('auth');

If you will use Laravel Sanctum, you need to protect routes (only if really needed)如果您将使用 Laravel Sanctum,则需要保护路由(仅在确实需要时)

Route::get('team', [CompanyController::class, 'index'])->middleware('auth:sanctum');

Documentation:文档:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM