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

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

问题描述

使用 Laravel 5.3 我已经设置了一个使用自己的 API 的网络应用程序.Passport 成功处理了身份验证.Web 应用程序在路由和模型策略中使用 auth 中间件进行授权.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?

任何帮助将不胜感激!

更新:成功了.

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

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 部分.

Laravel 现在将对所有 API 请求使用 api 防护.像 $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 防护.

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 防护.像 $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 应用程序使用自己的 API 和 Passport 的授权策略/门的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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