使用 Passport 认证后 请求修改 话题 This action is unauthorized

请求修改话题 api This action is unauthorized

1.可以确定该话题是这个用户的,因为这是刚刚创建的
2.将策略文件app\Policies\TopicPolicy.php直接返回ture,还是报This action is unauthorized
3.但是将app\Http\Controllers\Api\TopicsController.php文件中的$this->authorize('own', $topic);这个代码注释掉,他就会成功
4.将app\Http\Controllers\Api\TopicsController.php文件中的$this->authorize('own', $topic);注释取消掉,然后将app\Policies\TopicPolicy.php策略文件中return true;注释掉,通过web操作,是成功的。

使用 Passport 认证 后 This action is unauthorized

使用 Passport 认证 后 This action is unauthorized

使用 Passport 认证后 请求修改 话题 This action is unauthorized

使用 Passport 认证后 请求修改 话题 This action is unauthorized

2.策略文件

app\Policies\Policy.php

<?php

namespace App\Policies;

use Illuminate\Auth\Access\HandlesAuthorization;

class Policy
{
    use HandlesAuthorization;

    /**
     * 在所有策略之前
     * @param $user
     * @param $ability
     * @return bool
     */
    public function before($user, $ability)
    {
        #如果用户拥有管理内容的权限的话,即授权通过
        if ($user->can('manage_contents')) {
            return true;
        }
    }
}

app\Policies\TopicPolicy.php

<?php

namespace App\Policies;

use App\Models\User;
use App\Models\Topic;

class TopicPolicy extends Policy
{

    /**
     * @param User $user 授权文件当中第一个参数代表当前登陆用户
     * @param Order $order
     * @return bool
     */
    public function own(User $user, Topic $topic)
    {
        return true;
        return $user->isAuthorOf($topic);
    }
}

3.api控制器
app\Http\Controllers\Api\TopicsController.php

class TopicsController extends Controller\
{
.
.
.
    /**
     * 修改话题的方法
     * @param TopicRequest $request
     * @param Topic $topic
     * @return mixed
     */
    public function update(TopicRequest $request, Topic $topic)
    {
        $this->authorize('own', $topic);
        $topic->update($request->all());
        return $this->response->item($topic, new TopicTransformer());
    }
    .
    .
    .
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!