问题
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.
回答1:
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.
回答2:
Just use auth:api
middleware for routes with Policies
来源:https://stackoverflow.com/questions/41799974/authorization-policies-gates-for-laravel-5-3-web-app-consuming-own-api-w-passpo