Laravel 5.3 Web应用程序的授权策略/门使用带有Passport的自己的API [英] Authorization Policies/Gates for Laravel 5.3 web app consuming own API w/ Passport

查看:71
本文介绍了Laravel 5.3 Web应用程序的授权策略/门使用带有Passport的自己的API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Laravel 5.3,我已经建立了一个使用自己的API的网络应用.身份验证已成功通过Passport处理. Web应用程序在路由和模型策略中使用身份验证中间件进行授权. API路由使用默认的"auth:api"令牌防护来控制访问.

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.

我想在应用程序/策略中使用相同的策略来进行API授权以及网络身份验证,但是我不知道该怎么做.诸如$this->authorize('view', $model)之类的调用不起作用.我想我需要以某种方式将用户从Auth::guard('api')->user()传递到策略?

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?

任何帮助将不胜感激!

更新:可以正常工作了.

Update: Got it working.

似乎即使对于API调用,Laravel仍在使用Web防护中的用户来检查策略.未为API调用定义此用户.因此,我需要告诉Laravel,所有API调用都应使用api Guard.

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. 使用handle函数中的Auth::shouldUse('api');创建一个新的中间件.
  2. 将中间件分配给内核中的api部分.
  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现在将对所有API请求使用api Guard.像$this->authorize('view', $model)这样的调用在Web和api中都可以使用.

Laravel will now use the api guard for all API requests. Calls like $this->authorize('view', $model) will work in both web and api.

推荐答案

更新:使其正常工作.

似乎即使对于API调用,Laravel仍在使用Web防护中的用户来检查策略.未为API调用定义此用户.因此,我需要告诉Laravel,所有API调用都应使用api Guard.

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.

使用handle函数中的Auth::shouldUse('api');创建一个新的中间件. 将中间件分配给内核中的api部分. Laravel现在将对所有API请求使用api Guard.像$this->authorize('view', $model)这样的调用在Web和api中都可以使用.

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.

这篇关于Laravel 5.3 Web应用程序的授权策略/门使用带有Passport的自己的API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆