laravel 6 API资源策略索引

时间:2019-10-15 14:48:48

标签: laravel laravel-6

该策略不适用于index apiResource调用。始终返回403

我的ProjectPolicy是这样的:


class ProjectPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view any projects.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function viewAny(User $user)
    {
        return true;
    }
...

我的ProjectController使用了它:

class ProjectController extends Controller
{
    public function __construct()
    {
        $this->authorizeResource(ProjectPolicy::class, 'project');
    }
...

我注册了政策:


class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
        Project::class => ProjectPolicy::class,
    ];

index方法调用之外的所有方法都可以使用:

/**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        return $request->user()->projects()->get();
    }

1 个答案:

答案 0 :(得分:1)

在项目控制器构造函数中,您需要授权资源(模型)而不是策略本身

public function __construct()
{
    $this->authorizeResource(\App\Project::class, 'project');
}

还请确保发出请求的用户经过身份验证,不能授权来宾

但是如果您想要guests to be authorized,则可以在Policy类的依赖项注入上将User模型标记为可空/可选

/**
 * Determine whether the user can view any projects.
 *
 * @param  \App\User  $user
 * @return mixed
 */
public function viewAny(?User $user)
{
    return true;
}

希望这会有所帮助