政策退货无论采取何种措施,此操作都是未经授权的 [英] policy returns This action is unauthorized no matter what
问题描述
我只是想向有蚂蚁看的人展示公司 authServiceProvider:
i am just trying to show a company to anyone who ants to see it authServiceProvider:
Company::class => CompanyPolicy::class ,
'App\Models\Company' => 'App\Policies\CompanyPolicy',
companyPolicy
companyPolicy
public function view( Company $company)
{
return true ;
}
companyController
companyController
public function __construct(CompanyRepository $companies)
{
$this->companies = $companies;
}
public function show(Company $company)
{
$this->authorize('view', $company);
return $this->companyRepository->show($company);
}
路由到控制器:
Route::apiResource('companies', 'CompanyController');
它总是返回此操作是未授权的.为什么?
it always return This action is unauthorized. why?
推荐答案
AuthServiceProvier
行在您的AuthServiceProvier
中是多余的,您必须将其删除.
The line of Company::class => CompanyPolicy::class,
is redundant in your AuthServiceProvier
and you have to remove it.
让我举个例子:
假设我们有一个名为SomeModel
的模型,并已注册其策略.该策略具有view
的方法,该方法可以检查当前用户是否可以调用show方法.
assume we have a model named SomeModel
and have registered its policy. the policy has the method of view
which check current user is able to call show method.
对于api
的守护者,您可以创建如下的trait
:
For Guard of api
you may create a trait
like below:
trait ApiTrait
{
/**
* Authorize a given action for the current user.
*
* @param mixed $ability
* @param mixed|array $arguments
* @return \Illuminate\Auth\Access\Response
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function authorizeApi($ability, $arguments)
{
if (!request()->user('api')->can($ability, $arguments)) {
abort(403, 'This action is unauthorized.');
}
}
}
然后在您的控制器中使用它:
then in your controller use it:
class ExampleController extends Controller
{
use ApiTrait;
public function show(SomeModel $something)
{
$this->authorize('view', $something);
return 'it workes';
}
}
请注意,您应该使用auth:api
的中间件保护您的路由,否则在ApiTrait
中调用can
方法时会得到错误代码500.
pay attention you should protect your route with middleware of auth:api
or else you will get error code 500 when calling the can
method in ApiTrait
.
这篇关于政策退货无论采取何种措施,此操作都是未经授权的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!