Authorization Policies/Gates for Laravel 5.3 web app consuming own API w/ Passport

大憨熊 提交于 2019-12-08 04:18:17

问题


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.

  1. Create a new middleware with Auth::shouldUse('api'); in the handle function.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!