MattB's avatar
Level 2

Protecting API routes with middleware

Hi guys, so I'm trying to learn API routing on Laravel and so far it all works, but I would like to know how to protect the API from view. So far if anyone was to put in the API link into the address bar, you could see the entire JSON object. Is there a way to protect this using middleware like you can normal links? I have this as my links so far:

Route::apiResources([
    'user' => 'API\UsersController',
    'faq' => 'API\QuestionController',
    'dump' => 'API\DumpController',
    'gallery' => 'API\GalleryController',
    'artpack' => 'API\ArtPackController',
    'boughtArtPack' => 'API\BoughtArtPackController'
]);

Tried protecting it with an established auth middleware I have working for the admin back end routes but now it blocks the API whether you're logged in or not. I have it set up like this:

Route::group(['middleware' => 'IsAdmin'], function () {
  Route::apiResources([
    'user' => 'API\UsersController',
    'faq' => 'API\QuestionController',
    'dump' => 'API\DumpController',
    'gallery' => 'API\GalleryController',
    'artpack' => 'API\ArtPackController',
    'boughtArtPack' => 'API\BoughtArtPackController'
  ]);
});
0 likes
3 replies
MattB's avatar
Level 2

Isn't that for when data needs to be accessed by a 3rd party app that isn't Laravel? Is there not a simpler way to protect the API when it's just kept in the laravel app?

Nakov's avatar

There is. You can just create Policies, and authorize the users for the access in the controller, instead of the middleware.

Please or to participate in this conversation.