Laravel UserPolicy始终拒绝授权

时间:2018-04-17 17:28:53

标签: laravel laravel-5 laravel-5.6

我在Laravel中创建了一个UserPolicy,并尝试在控制器中使用$this->authorize(User::class),但是,当我访问UserController@index时,它始终返回403错误,此问题不是&如果我从$this->authorize(User::class)

中移除UserController,则会出现#39;

应用/提供者/ AuthServiceProvider.php     

namespace App\Providers;

use App\Transaction;
use App\Policies\UserPolicy;
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 = [
        User::class => UserPolicy::class
    ];

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

        //
    }
}

应用/策略/ UserPolicy.php     

namespace App\Policies;

use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class UserPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can index users.
     *
     * @param  \App\User  $model
     * @return mixed
     */
    public function index(User $user)
    {
        return true;
    }
}

应用/控制器/ UserController.php     

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->authorize(User::class);
        $users = User::all();
        return view('users.index', compact('users'));
    }
}

1 个答案:

答案 0 :(得分:1)

use App\User;缺少

app/Providers/AuthServiceProvider.php,感谢Mike Foxtech感谢answer in the comments

  

在app / Providers / AuthServiceProvider.php中添加使用App \ User;