简体   繁体   中英

Laravel REST protect given methods and make accessable per role

I have a laravel project which provides over rest api some public data on the other hand logged in users can manage some membership related datas.

Now in this dashboard I have couple of react components. Some of theme are simply fetching async datas and there are some which are interacting with the database in the meaning they patch, create, delete datas in function of user role. This endpoints should be protected.

I read about sanctum but I think for this scenario would be overhead. Is there any other approach to protect this api routes?

You can make it easy with laravel Auth. You need to add api_token field to your users table, if you don't have it. Generate access_token on register of the user. For protection of the route as middleware use auth:api.

In app\Http\Kernel.php you need to add api key to the $middlewareGroups

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

After that add middleware guard to the route

Route::group(['middleware' => 'auth:api'], function () {}

When you are making request you need to add api_token param to your url ex: http://localhost/update?api_token=1234. This is the easiest way that I know. You can also send api_token as part of the body of the request to be secure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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