drba1172 2019-07-27 10:48
浏览 123

授权或者方法总是为laravel策略返回false

I'm having trouble setting up policy in Laravel. I'm using Laravel voyager admin panel that comes integrated with Laravel policy concept. I have created policy for content model and assigned it to Content BREAD. Just to check the result, I simply returned true in view function. And yet, it still returns false.

Here is a snippet from ContentPolicy class:

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

and here in ContentController:

    public function view(Request $request)
    {
        $content=Content::all();

        return var_dump($this->authorize("view",$content));
    }

and here I registered my policy

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

    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        Passport::routes();

        //
    }
}

It is worth to note that 'browse_admin' works fine in such case for laravel voyager.

I appreciate your help. Thanks in advance

  • 写回答

2条回答 默认 最新

  • doujishao8793 2019-07-27 10:54
    关注

    Based on Laravel Documentation you should register your policies in AuthServiceProvider like this:

    <?php
    
    namespace App\Providers;
    
    use App\Content;
    use App\Policies\ContentPolicy;
    use Illuminate\Support\Facades\Gate;
    use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
    
    class AuthServiceProvider extends ServiceProvider
    {
        /**
         * The policy mappings for the application.
         *
         * @var array
         */
        protected $policies = [
            Content::class => ContentPolicy::class,
        ];
    
        /**
         * Register any application authentication / authorization services.
         *
         * @return void
         */
        public function boot()
        {
            $this->registerPolicies();
    
            //
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?