Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ycsm's avatar
Level 1

api_token working - but how to authorize access to API's by roles/permissions?

Hello. I'm struggling to get this basic concept off the ground, and have actually found little to no literature on the internet on how to do this. I want to restrict access to API routes (either on the controller level or the route level) to different roles.

Currently I have 3 levels of control setup on a laravel project and it all works perfectly on the web side. I'm using laravel's built in guards and no extra packages like spatie or bouncer.

However, when attempting to figure out how to set access levels on API's I am really struggling (the API's are all local). I have setup an api_token in the users table and I can successfully restrict access - but, I can only differentiate between a guest and a user who is logged in. I have no way to differentiate what type of user it is.

Is there some basic concept I've missed here? If you'd like to see any specific code please let me know!

Thank you

Nick

0 likes
2 replies
ycsm's avatar
Level 1

Hi Jeffrey, Thanks for the post!

I saw a little bit of information in your first link that I hadn't spotted before.

THIS DIDN'T WORK (it would work in web.php):

    Route::post('privacy_change', 'UsersController@privacy_change')->middleware('can:change_privacy');

THIS WORKED!

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

    Route::post('privacy_change', 'UsersController@privacy_change')->middleware('can:change_privacy');

});

Apparently because of this bit of information I found, which I had no knowledge of before... "Out of the box, the web middleware group is automatically applied to your routes/web.php file by the RouteServiceProvider."

It is now working!! I just needed to wrap the API routes

Please or to participate in this conversation.