Using Laravel 5.3 I've set up a web app that consumes its own API. Authentication successfully handled by Passport. Web app uses auth middleware in routes and Model Policies for authorization. API routing uses default 'auth:api' token guard to control access.
I would like to use the same Policies in app/Policies for API authorization as well as the web auth, but I don't understand how. Calls such as $this->authorize('view', $model)
do not work. I guess I need to pass the user from Auth::guard('api')->user()
to the Policies somehow?
Any help would be appreciated!
Update: Got it working.
Seems that even for the API calls Laravel was still using the user from the web guard to check against policies. This user is undefined for API calls. So I needed to tell Laravel that all API calls should use the api guard.
- Create a new middleware with
Auth::shouldUse('api');
in the handle function. - Assign the middleware to the api section in the kernel.
Laravel will now use the api guard for all API requests. Calls like $this->authorize('view', $model)
will work in both web and api.