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

ycsm's avatar
Level 1

Laravel - Using Gates on API requests for authorization

I have a laravel app setup perfectly with roles and permissions using gates. For example, in the web routes file I have this which works great:

WEB.PHP

Route::resource('groups', 'SuperAdmin\GroupsController')->middleware('can:SEE-admin-dashboard');

However, when I try to apply the same middleware to API requests (inside Vue Components), it will not work. I keep getting unauthorised messages. Here are two things I've tried..

API.PHP

Attempt 1-

Route::post('group_times', 'TimesController@custom_groups_times')->middleware('can:SEE-admin-dashboard');

Attempt 2-

Route::middleware('auth:api')->post('group_times', 'TimesController@custom_groups_times', function(Request $request) {
    return $request->user();
});

I'm getting a 401 unauthorised message:

401 Unauthorised

I have setup each user with an API token as mentioned in the Laravel docs. Like so, but no such luck.

401 unauthorized: https://imgur.com/het8wEf

Am I missing something here? Do I have to pass any tokens? What is the best way to achieve authentication over an API request that still uses the gates? Is this possible? I've been learning Laravel over the last few weeks and this really is my first major stumbling block

Here is the code from AuthServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();


        // Implicitly grant "Super Admin" role all permissions
        // This works in the app by using gate-related functions like auth()->user->can() and @can()
        Gate::before(function ($user, $ability){
            return $user->hasRole('Super Admin') ? true : null;
        });

        //Superadmin check
        Gate::define('isSuperAdmin', function($user){
            return $user->hasRole('Super Admin');
        });

        //PLT Student check
        Gate::define('isPLTStudent', function($user){
            return $user->hasRole('PLT Student');
        });

        //Student check
        Gate::define('isStudent', function($user){
            return $user->hasRole('Student');
        });

        //SEE Admin Panel
        Gate::define('SEE-admin-panel', function($user){
            return $user->hasAnyRoles(['PLT Student']);
        });

        //SEE Admin Dashboard
        Gate::define('SEE-admin-dashboard', function($user){
            return $user->hasAnyRoles(['PLT Student']);
        });

        //USERS PERMISSIONS

            //Overall
            Gate::define('USERS-manage-users', function($user){
                return $user->hasAnyRoles(['PLT Student']);
            });

            //Specific
            Gate::define('USERS-create-users', function($user){
                return $user->hasRole('PLT Student');
            });
            Gate::define('USERS-view-users', function($user){
                return $user->hasRole('PLT Student');
            });
            Gate::define('USERS-edit-users', function($user){
                return $user->hasRole('PLT Student');
            });
            Gate::define('USERS-delete-users', function($user){
                return $user->hasRole('PLT Student');
            });

        //RUNS PERMISSIONS

        //Overall
        Gate::define('RUNS-manage-runs', function($user){
            return $user->hasAnyRoles(['PLT Student']);
        });

        //Specific
        Gate::define('RUNS-create-runs', function($user){
            return $user->hasRole('PLT Student');
        });
        Gate::define('RUNS-view-runs', function($user){
            return $user->hasAnyRoles(['PLT Student', 'Student']);
        });
        Gate::define('RUNS-edit-runs', function($user){
            return $user->hasRole('PLT Student');
        });
        Gate::define('RUNS-delete-runs', function($user){
            return $user->hasRole('PLT Student');
        });
        Gate::define('RUNS-delete-runs', function($user){
            return $user->hasRole('PLT Student');
        });

    //RUNTYPES PERMISSIONS

        //Overall
        Gate::define('RUNTYPES-manage', function($user){
            //return $user->hasAnyRoles(['PLT Student']);
        });

        //Overall
        Gate::define('RUNTYPES-view', function($user){
            return $user->hasAnyRoles(['PLT Student', 'Student']);
        });

    //RUNTYPES PERMISSIONS

        //Overall
        Gate::define('GROUP-manage', function($user){
            //return $user->hasAnyRoles(['PLT Student']);
        });
    }

}

Vue axios:

//Get time data to populate table
            getTimes(){
        axios.post('/api/group_times', {
                group_id: this.group_id,
                amount: 5,
                season_id: this.season_id
            })
                .then(response => {
                        this.times = response.data;
                    }
                );
        },
0 likes
3 replies
f7n's avatar

@ycsm So the answer here is to wrap the route in the auth:api middleware? Then the Gate can understand the $user from the Authorization token? is that correct?

f7n's avatar

My gate is defined as the following:

Gate::define('view-own-user-profile', function ($user, $profile) {
     return $user->id == $profile->id;
});

How can I use this in my api.php route file? The user is authenticating using a JWT token in the header. I don't think it's possible, right? I have to use this gate in the controller.

Can anyone help?

Please or to participate in this conversation.